索引器是一组get和set的访问器,与属性类似。
public string this[int index]
{
get
{
}
set
{
}
}
01:索引器不用分配内存来存储
02:主要用来访问其他数据成员,并为他们提供获取和设置的方法
public class MyClass
{
public string LastNmae;
public string NextNmae;
public string this[int index]
{
get
{
switch (index)
{
case 0:
return LastNmae;
break;
case 1:
return NextNmae;
break;
default:
return null;
break;
}
}
set
{
switch (index)
{
case 0:
LastNmae = value;
break;
case 1:
NextNmae = value;
break;
default:
throw new Exception("Erro");
break;
}
}
}
}
MyClass myClass=new MyClass();
myClass[0] = "22";
myClass[1] = "介家店";
Console.WriteLine(myClass[0]);
Console.WriteLine(myClass[1]);
Console.ReadKey();**加粗样式**