Indexer,索引,或译作索引器,可以使对象利用类似于数组的下标来访问类中的数据成员。
其语法为
修饰符 类型 this (参数列表)
{
get
{
//获取数据成员
}
set
{
//设置数据成员
}
}
其中,this指当前对象。get和set的语法和属性(property)很相像。只不过多了索引参数。
和方法一样,索引也可以重载。其重载是通过参数列表来区分的。
public class IndexerRecord 
...{
private string[] keys = ...{
"Author","Publisher","Title","Subject","ISBN","Content"
};
private string[] data = new string[6];
//索引
public string this[int index]
...{
set
...{
this.data[index] = value;
}
get
...{
return data[index];
}
}
//索引重载
public string this[string key]
...{
set
...{
int index = FindKey(key);
this.data[index] = value;
}
get
...{
int index = FindKey(key);
return data[index];
}
}
private int FindKey(string key)
...{
int len = data.Length;
for(int i = 0; i < len ; i++)
...{
if(keys[i]==key)
return i;
}
return -1;
}
public static void Main()
...{
IndexerRecord r = new IndexerRecord();
//索引set操作
r[0] = "zhaohongliang";
r[2] = "C# Indexer Test";
//索引get操作
System.Console.WriteLine(r["Author"]);
System.Console.WriteLine(r["Title"]);
}
}zhaohongliang
C# Indexer Test
451

被折叠的 条评论
为什么被折叠?



