Csharp/C#教程:谈谈c#中的索引器分享

概念

索引器(Indexer)允许类中的对象可以像数组那样方便、直观的被引用。当为类定义一个索引器时,该类的行为就会像一个虚拟数组(virtualarray)一样。

索引器可以有参数列表,且只能作用在实例对象上,而不能在类上直接作用。

可以使用数组访问运算符([])来访问该类的实例。

索引器的行为的声明在某种程度上类似于属性(property)。属性可使用get和set访问器来定义索引器。但是属性返回或设置的是一个特定的数据成员,而索引器返回或设置对象实例的一个特定值。

定义一个一维数组的索引器:

element-typethis[intindex] { //get访问器 get { //返回index指定的值 } //set访问器 set { //设置index指定的值 } }

提示:索引器必须以this关键字定义,this是类实例化之后的对象

实例:

usingSystem; namespaceC_Pro { publicclassStudent { privatestringname; privatestringgrade; publicstringName { get{returnname;} set{name=value;} } publicstringGrade { get{returngrade;} set{grade=value;} } //定义索引器 publicstringthis[intindex] { get { if(index==0)returnname; elseif(index==1)returngrade; elsereturnnull; } set { if(index==0)name=value; elseif(index==1)grade=value; } } staticvoidMain(string[]args) { Students=newStudent(); s[0]="Jeson"; s[1]="First-year"; Console.WriteLine(s.Name); Console.WriteLine(s.Grade); Console.ReadKey(); } } }

运行后结果:

Jeson
First-year

重载索引器

索引器(Indexer)可被重载。索引器声明的时候也可带有多个参数,且每个参数可以是不同的类型。没有必要让索引器必须是整型的。C#允许索引器可以是其他类型,例如,字符串类型。

usingSystem; namespaceC_Pro { publicclassIndexedNames { privatestring[]namelist={"a","b","c","d"}; //输入namelist的index返回对应的值 publicstringthis[intindex] { get { returnnamelist[index]; } set { namelist[index]=value; } } //输入namelist的值,返回对应的索引 publicintthis[stringname] { get { for(inti=0;i<namelist.Length;i++) { if(namelist[i]==name)returni; } return-1; } } staticvoidMain(string[]args) { IndexedNamesname=newIndexedNames(); Console.WriteLine(name[1]); Console.WriteLine(name["a"]); } } }

运行后结果:

b

0

索引器与数组的区别:

索引器的索引值(Index)类型不限定为整数,用来访问数组的索引值(Index)一定为整数,而索引器的索引值类型可以定义为其他类型。 索引器允许重载,一个类不限定为只能定义一个索引器,只要索引器的函数签名不同,就可以定义多个索引器,可以重载它的功能。 索引器不是一个变量,索引器没有直接定义数据存储的地方,而数组有。索引器具有Get和Set访问器。

索引器与属性的区别:

索引器以函数签名方式this来标识,而属性采用名称来标识,名称可以任意。 索引器可以重载,而属性不能重载。 索引器不能用static来进行声明,而属性可以。索引器永远属于实例成员,因此不能声明为static。

上述就是C#学习教程:谈谈c#中的索引器分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/903755.html

(0)
上一篇 2021年10月21日
下一篇 2021年10月21日

精彩推荐