C#通过提供索引器(indexer),使得用户可以像处理数组一样对对象使用下标。索引器为我们提供了通过索引方式访问类的数据的方法。
例:
例:
using System;
namespace suoyinqi
{
class Vector
{
private double x,y,z;
public double this[int i]//定义索引器,使得可以使用数组的方式访问Vector的数据
{
get
{
switch(i)
{
case 0:
return x;
case 1:
return y;
case 2:
return z;
default:
throw new IndexOutOfRangeException("访问下标超出范围!");//若访问下标超出范围,抛出异常
}
}
set
{
switch(i)
{
case 0:
x = value;
break;
case 1:
y = value;
break;
case 2:
z = value;
break;
default:
throw new IndexOutOfRangeException("访问下标超出范围!");//若访问下标超出范围,抛出异常
}
}
}
}
public class Class1
{
[STAThread]
public static void Main(string[] args)
{
Vector v = new Vector();
v[0] = 4;
v[1] = 5;
v[2] = 6;
Console.WriteLine("Vector.x = {0}",v[0]);
Console.WriteLine("Vector.y = {0}",v[1]);
Console.WriteLine("Vector.z = {0}",v[2]);
}
}
}
namespace suoyinqi
{
class Vector
{
private double x,y,z;
public double this[int i]//定义索引器,使得可以使用数组的方式访问Vector的数据
{
get
{
switch(i)
{
case 0:
return x;
case 1:
return y;
case 2:
return z;
default:
throw new IndexOutOfRangeException("访问下标超出范围!");//若访问下标超出范围,抛出异常
}
}
set
{
switch(i)
{
case 0:
x = value;
break;
case 1:
y = value;
break;
case 2:
z = value;
break;
default:
throw new IndexOutOfRangeException("访问下标超出范围!");//若访问下标超出范围,抛出异常
}
}
}
}
public class Class1
{
[STAThread]
public static void Main(string[] args)
{
Vector v = new Vector();
v[0] = 4;
v[1] = 5;
v[2] = 6;
Console.WriteLine("Vector.x = {0}",v[0]);
Console.WriteLine("Vector.y = {0}",v[1]);
Console.WriteLine("Vector.z = {0}",v[2]);
}
}
}