C#(.NET)索引器
1、索引器跟属性很像,只不过他有一个this关键字紧矿返跟着是[int index],下面具体用代码来做一个自己的索引器。
2、创建一个省份的类province,紧著夏跟着添加两个私有变量
private string FirstCity="广州";
private string SecondCity="佛山";
然后创建索引器为私有变量复制或取值
public string this[int index]
{
set
{
if(index==1)
{
FirstCity= value;
}
else if (index == 2)
{
SecondCity= value;
}
else
{
throw new Exception("错误的序号");
}
} 趴罪爱
get
{
if (index == 1)
{
return FirstCity;
}
else if (index == 2)
{
return SecondCity;
}
else
{
throw new Exception("错误的序号");
}
}
至此,索引器已经创建好了,您可以像数组一样通过[]来获取和赋值索引器了,是不是很方便?
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
阅读量:106
阅读量:112
阅读量:139
阅读量:181
阅读量:105