当前位置: 移动技术网 > IT编程>开发语言>c# > C#面向对象--索引器

C#面向对象--索引器

2020年04月01日  | 移动技术网IT编程  | 我要评论

  一、索引器(indexer)允许类和结构的实例像数组一样通过索引取值,可以看做是对[]运算符的重载,索引器实际上就是有参数的属性,也被称为有参属性或索引化属性,其声明形式与属性相似,不同之处在于索引器的访问器需要传入参数;
  1.声明索引器:

class myclass
{
    string[] myarray = new string[100];
    public string this[int index] //使用关键字this定义索引器
    {
        get
        {
            return myarray[index];
        }
        set
        {
            myarray[index] = value;
        }
    }
}
//使用索引器:
myclass myclass = new myclass();
myclass[0] = "1";
console.writeline(myclass[0]); //1

  ※属性和索引器都不被当作变量,二者都是在基于方法实现的,因此无法将属性或索引器作为引用参数、引用返回值、引用局部变量来传递和使用;

  ※索引器只能声明为实例成员,不能声明为静态的;

  ※索引器不支持自动实现;

  ※索引器只是在调用的写法上与数组相同,但实现原理与数组完全不同,二者不可混淆;

  2.声明泛型版本的索引器:

class myclass<t>
{
    private t[] myarray = new t[100];
    public t this[int index]
    {
        get
        {
            return myarray[index];
        }
        set
        {
            myarray[index] = value;
        }
    }
}
//使用索引器:
myclass<string> myclass = new myclass<string>();
myclass[0] = "1";
console.writeline(myclass[0]); //1

  3.索引器不仅可以根据整数进行索引,还可以根据任何类型进行索引,同时索引器也支持重载,类似于方法的重载,需要参数列表不完全相同,例如:

public int this[string content]
{
    get
    {
        return array.indexof(myarray, content);
    }
}

  4.索引器同时也支持参数列表有多个参数,类似于使用多维数组,例如:

string[,] myarray = new string[100, 100];
public string this[int posx, int posy]
{
    get
    {
        return myarray[posx, posy];
    }
    set
    {
        myarray[posx, posy] = value;
    }
}
//使用索引器:
myclass myclass = new myclass();
myclass[0, 0] = "1";
console.writeline(myclass[0, 0]); //1

  二、索引器实际上就是有参数的属性,其属性名固定为item,通过反射获取myclass的属性信息数组即可看到:

type mytype = typeof(myclass);
propertyinfo[] myproperties = mytype.getproperties();
for (int i = 0; i < myproperties.length; i++)
{
    console.writeline(myproperties[i].name); //item
}

  1.通过反射调用索引器获取值:

myclass myclass = new myclass();
for (int i = 0; i < 100; i++)
{
    myclass[i] = i.tostring();
}
propertyinfo data = mytype.getproperty("item");
//如果索引器包含重载,例如上面this[string content]的例子,那么使用getproperty的重载方法传入参数列表的类型数组来获取指定索引器mytype.getproperty("item", new type[] { typeof(int) })
string mystr = (string)data.getvalue(myclass, new object[] { 5 }); //第二个参数即索引器参数
console.writeline(mystr); //5

  2.查看其il代码:

 

  


如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的认可是我写作的最大动力!

作者:minotauros
出处:

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网