宏昌电子珠海新厂竣工:C#索引器的作用
来源:百度文库 编辑:杭州交通信息网 时间:2024/05/04 22:11:26
谁能告诉我在C#索引器的作用?
C#索引器的作用
C#通过提供索引器,可以象处理数组一样处理对象。特别是属性,每一个元素都以一个get或set方法暴露。
public class Skyscraper
{
Story[] stories;
public Story this [int index]
{
get
{
return stories [index];
}
set
{
if (value != null)
{
stories [index] = value;
}
}
}
//...
}
Skyscraper empireState = new Skyscraper (/*...*/);
empireState [102] = new Story ("The Top One", /*...*/);
【译注:索引器最大的好处是使代码看上去更自然,更符合实际的思考模式】