C#的索引器和C++中重写[]运算符的作用相同.
如果为类定义一个索引器, 就可以告诉编译器, 如果编译器遇到把类实例当作数组的代码, 该怎么办.
定义索引器的方式与定义属性的方式一样, 也使用get和set函数, 主要的区别是索引器的名称是关键字this, 要为Vector定义索引器, 就可以修改类的定义, 代码如下:
using
System;
using
System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualBasic;
namespace CSharp_Text
{
struct Vector
{
public double x, y, z;
public Vector( double x, double y, double z)
{
this .x = x;
this .y = y;
this .z = z;
}
public override string ToString()
{
return " ( " + x + " , " + y + " , " + z + " ) " ;
}
public double this [ int i]
{
get
{
switch (i)
{
case 0 :
return x;
case 1 :
return y;
case 2 :
return z;
default :
throw new IndexOutOfRangeException( " Attempt to retrieve Vector element " + i);
}
}
set
{
switch (i)
{
case 0 :
x = value;
break ;
case 1 :
y = value;
break ;
case 2 :
z = value;
break ;
default :
throw new IndexOutOfRangeException( " Attempt to set Vector element " + i);
}
}
}
}
class main
{
static void Main()
{
Vector vect1 = new Vector( 1 , - 2 , 4.1 );
Vector vect2 = new Vector();
Console.WriteLine( " vect1 = " + vect1);
Console.WriteLine( " vect1[1] = " + vect1[ 1 ]);
for ( int i = 0 ; i < 3 ; i ++ )
{
vect2[i] = i;
}
Console.WriteLine( " vect2 = " + vect2);
}
}
}
using System.Linq;
using System.Text;
using Microsoft.VisualBasic;
namespace CSharp_Text
{
struct Vector
{
public double x, y, z;
public Vector( double x, double y, double z)
{
this .x = x;
this .y = y;
this .z = z;
}
public override string ToString()
{
return " ( " + x + " , " + y + " , " + z + " ) " ;
}
public double this [ int i]
{
get
{
switch (i)
{
case 0 :
return x;
case 1 :
return y;
case 2 :
return z;
default :
throw new IndexOutOfRangeException( " Attempt to retrieve Vector element " + i);
}
}
set
{
switch (i)
{
case 0 :
x = value;
break ;
case 1 :
y = value;
break ;
case 2 :
z = value;
break ;
default :
throw new IndexOutOfRangeException( " Attempt to set Vector element " + i);
}
}
}
}
class main
{
static void Main()
{
Vector vect1 = new Vector( 1 , - 2 , 4.1 );
Vector vect2 = new Vector();
Console.WriteLine( " vect1 = " + vect1);
Console.WriteLine( " vect1[1] = " + vect1[ 1 ]);
for ( int i = 0 ; i < 3 ; i ++ )
{
vect2[i] = i;
}
Console.WriteLine( " vect2 = " + vect2);
}
}
}
运行结果:
虽然可以用for, do和while循环来处理索引器, 但不能使用foreach循环. 因为foreach循环语句的工作方式不同, 它把元素当作一个集合, 而不是一个数组.