索引器

索引器允许类或结构的实例就像数组一样进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。索引器在语法上方便您创建客户端应用程序可将其作为数组访问的结构接口。索引器经常是在主要用于封装内部集合或数组的类型中实现的。索引器表示法不仅简化了客户端应用程序的语法,还使其他开发人员能够更加直观地理解类及其用途。

要声明类或结构上的索引器,请使用 this 关键字,如下例所示:

public int this[int index]    // Indexer declaration
{
    
// get and set accessors
}

索引器概述

  • 使用索引器可以用类似于数组的方式为对象建立索引。

  • get 访问器返回值。set 访问器分配值。

  • this 关键字用于定义索引器。

  • value 关键字用于定义由 set 访问器分配的值。

  • 索引器不必根据整数值进行索引,由您决定如何定义特定的查找机制。

  • 索引器可被重载。

  • 索引器可以有多个形参,例如当访问二维数组时。

  • 备注

    索引器类型及其参数类型必须至少如同索引器本身一样是可访问的。有关可访问级别的更多信息,请参见访问修饰符

    有关如何对接口使用索引器的更多信息,请参见接口索引器

    索引器的签名由其形参的数量和类型组成。它不包括索引器类型或形参名。如果在同一类中声明一个以上的索引器,则它们必须具有不同的签名。

    索引器值不属于变量;因此,不能将索引器值作为 refout 参数进行传递。

    示例

    下面的示例说明如何声明私有数组字段、temps 和索引器。使用索引器可直接访问实例 tempRecord[i]

    class TempRecord
    {
        
    // Array of temperature values
        private float[] temps = new float[10] { 56.2F56.7F56.5F56.9F58.8F
                                                
    61.3F65.9F62.1F59.2F57.5F };

        
    // To enable client code to validate input 
        
    // when accessing your indexer.
        public int Length
        {
            
    get { return temps.Length; }
        }
        
    // Indexer declaration.
        
    // If index is out of range, the temps array will throw the exception.
        public float this[int index]
        {
            
    get
            {
                
    return temps[index];
            }

            
    set
            {
                temps[index] 
    = value;
            }
        }
    }

    class MainClass
    {
        
    static void Main()
        {
            TempRecord tempRecord 
    = new TempRecord();
            
    // Use the indexer's set accessor
            tempRecord[3= 58.3F;
            tempRecord[
    5= 60.1F;

            
    // Use the indexer's get accessor
            for (int i = 0; i < 10; i++)
            {            
               System.Console.WriteLine(
    "Element #{0} = {1}", i, tempRecord[i]);            
            }

            
    // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();

        }
    }


    原文地址:https://www.cnblogs.com/greatandforever/p/1787070.html