zoukankan      html  css  js  c++  java
  • C#索引器

    索引器允许类或结构的实例就像数组一样进行索引。 索引器类似于属性,不同之处在于它们的取值函数采用参数。

    在下面的示例中,定义了一个泛型类,并为其提供了简单的 get 和 set 取值函数方法(作为分配和检索值的方法)。 Program 类创建了此类的一个实例,用于存储字符串。

    class SampleCollection<T>
    {
        // Declare an array to store the data elements.
        private T[] arr = new T[100];
    
        // Define the indexer, which will allow client code
        // to use [] notation on the class instance itself.
        // (See line 2 of code in Main below.)        
        public T this[int i]
        {
            get
            {
                // This indexer is very simple, and just returns or sets
                // the corresponding element from the internal array.
                return arr[i];
            }
            set
            {
                arr[i] = value;
            }
        }
    }
    
    // This class shows how client code uses the indexer.
    class Program
    {
        static void Main(string[] args)
        {
            // Declare an instance of the SampleCollection type.
            SampleCollection<string> stringCollection = new SampleCollection<string>();
    
            // Use [] notation on the type.
            stringCollection[0] = "Hello, World";
            System.Console.WriteLine(stringCollection[0]);
        }
    }
    // Output:
    // Hello, World.

    表达式主体定义

    直接只返回表达式结果的索引器很常见。 下面的语法快捷方式使用 => 来定义这些索引器:

    public Customer this[long id] => store.LookupCustomer(id);

    索引器必须为只读,并且你不能使用 get 取值函数关键字。

    索引器概述
    使用索引器可以用类似于数组的方式为对象建立索引。
    get 取值函数返回值。 set 取值函数分配值。
    this 关键字用于定义索引器。
    value 关键字用于定义由 set 索引器分配的值。
    索引器不必根据整数值进行索引;由你决定如何定义特定的查找机制。
    索引器可被重载。
    索引器可以有多个形参,例如当访问二维数组时

  • 相关阅读:
    又学到的2个小技巧
    CSS3 简写animation
    CSS3 区别Transform,Transition,Animation一句话
    纠错【2012年5月9日 JQuery跑马灯(文字无缝向上翻动)(自已封装的第三个插件)】
    jQuery计算选中的文本字数,并弹出一个层(插件四)
    html5Canvas绘制线条closePath();
    html5循环方式绘制矩形
    jQuery过滤not()与filter();
    javascript在firebug调试时用console.log
    jQuery插件在光标定位的地方插入文字(插件5)
  • 原文地址:https://www.cnblogs.com/rinack/p/5676324.html
Copyright © 2011-2022 走看看