VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • C#面向对象--索引器

 一、索引器(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
出处:https://www.cnblogs.com/minotauros/

 

相关教程