C#(.NET)索引器

 时间:2026-04-24 02:05:25

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

}

}

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

  • 图片的3D溶化效果怎么制作
  • 3D打印技术如何制作“地球”灯?
  • 3ds max散布之源对象参数如何设置
  • 3ds Max时尚登模型制作
  • 3dsmax圆柱体如何设置高度分段为1
  • 热门搜索
    万茜个人资料简介 无聊的时候怎么办 晚间西红柿减肥 上海到普陀山旅游攻略 倩女幽魂攻略 特仑苏牛奶怎么样 英雄无敌3攻略 海南旅游攻略自由行 李子吃多了会怎么样 新飞燃气灶怎么样