C#(.NET)索引器

时间:2026-02-13 10:31:45

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("错误的序号");

}

}

至此,索引器已经创建好了,您可以像数组一样通过[]来获取和赋值索引器了,是不是很方便?

© 2026 一点知道
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com