示例
using System;
namespace Test
{
class Girls
{
private string [] names=new string[5];
public string this[int n]
{
get{ return names[n]; }
set { names[n]=value; }
}
}
class Program
{
[STAThread]
static void Main(string [] args)
{
Girls gls=new Girls();
gls[0]="小婵"; // 赋值调用set访问器
string r=gls[0]; // 读取调用get访问器
Console.WriteLine("{0}",r);
}
}
}
其实我们可以定义两个方法来代替这个索引器:
class Girls
{
private string [] names=new string[5];
public string get_Item(int n)
{
return names[n];
}
public void set_Item(int n,string _value)
{
names[n]=_value;
}
}
现在我们做一个大胆的设想,如果我们将上面代码和前面的索引器代码放在一起会怎样?
class Girls
{
private string [] names=new string[5];
public string this[int n]
{
get { return names[n];}
set { names[n]=value ; }
}
public string get_Item(int n)
{
return names[n];
}
public void set_Item(int n,string _value)
{
names[n]=_value;
}
}
结果如你所想,编译时会显示方法已经定义的错误。我们知道上面的索引器编译后会生成get_Item和set_Item两个方法,而现在我们又定义了和这两个方法完全相同的方法,当然是重定义了。索引器最常用的是定义字符串索引参数,如“public MyObject this[string name]”,下面是一个综合示例,里面使用了属性、重载的索引器,你从中可以更加了解属性和索引器的用法:
using System;
namespace TestSpace
{
public class CD
{
public string name; // CD名称
public double price; //CD价格
public string type; // CD类型
public CD(string n,double p,string t)
{ name=n;price=p;type=t; }
}
public class VideoShop
{
private CD [] cdCollection =new CD[10000]; //商店CD集合
private int cdCount=0; //CD数目
public int Count { get { return cdCount; } } // 返回当前CD数目
public CD this[string cdName]
{
get
{
//按CD名称返回CD对象
foreach(CD t in cdCollection)
if(t.name==cdName) return t;
return null;
}
}
public CD this[string cdName,string type]
{
get
{
//按CD名称和类型返回CD对象
foreach(CD t in cdCollection)
if (t.name==cdName && t.type==type) return t;
return null;
}
}
public CD this[int n]
{
set
{
//如果是商店里没有此CD则cdCount增加
if (cdCollection[n] == null ) cdCount++;
if (value == null && cdCollection[n] != null )
cdCount--;
cdCollection[n]=value;
}
get { return cdCollection[n]; }
}
}
class Test
{
[STAThread]
static void Main(string [] args)
{
VideoShop myshop =new VideoShop();
CD cd1=new CD("误入歧途",10.5,"DVD");
CD cd2=new CD("罗马假日",5.5,"VCD");
myshop[myshop.Count]=cd1;//调用索引器赋值
myshop[myshop.Count]=cd2;//调用索引器赋值
CD a=myshop["罗马假日"];//调用索引器按名称获得CD
CD b=myshop["误入歧途","DVD"];//调用索引器按类型和名称获得CD
Console.WriteLine("名称:{0}{1},价格:{2}",a.type,a.name,a.price);
Console.WriteLine("名称:{0}{1},价格:{2}",b.type,b.name,b.price);
}
}
}
运行结果:
名称:VCD 罗马假日,价格:5.5
名称:DVD 误入歧途,价格:10.5
为了方便,在上面例子中直接定义了带有公开字段的CD类,当然我们不提倡这么用。然后我们定义了音像商店类VideoShop,并在这个商店类里定义了大量的索引器。实际上这个例子还是不能完全阐明索引器及属性的所有用法。要想真正掌握索引器和属性的用法,还得仔细查看它们生成的中间代码,因为那才是它们的庐山真面目。