索引符或叫索引器,是将类或结构的实例转为数租,按数组的方式设置和获取元素值 。索引符可以看做[]运算符的重载。
索引符常用于表示某些数据结构的类、数组、列表和映射等,并可以在.Net基类中定义这些结构体。也可用于引用类型的转换。
索引符和数组比较:
(1)索引符的索引值(Index)类型不受限制
(2)索引符允许重载
(3)索引符不是一个变量
索引符和属性的不同点
(1)属性以名称来标识,索引符以函数形式标识
(2)索引符可以被重载,属性不可以
(3)索引符不能声明为static,属性可以。
using System;
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 Vector(Vector rhs)
{
x = rhs.x;
y = rhs.y;
z = rhs.z;
}
//继承Object的Tostring()
public override string ToString()
{
return"("+x+","+y+","+z+")";
}
//定义索引
public double this[int i]
{
get
{
switch(i)
{
case 0:
return this.x;
case 1:
return this.y;
case 2:
return this.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);
}
}
}
public static void Main()
{
Vector Vect1 = new Vector(1.0,-5.0,4.6);
Vector Vect2 = new Vector();
Console.WriteLine("Vect1 = "+Vect1);
Console.WriteLine("Vect[i] = "+Vect1[0]); //使用数组下标获取元素
for(int i=0;i<3;i++)
{
Vect2[i] = i;
}
Console.WriteLine("Vect2 = "+Vect2);
Console.WriteLine("Vect2 = "+Vect2[2]);
}
}