C#索引器

索引器允许类或结构的实例就像数组一样进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。索引器经常是在主要用于封装内部集合或数组的类型中实现的。

索引器概述

  • 使用索引器可以用类似于数组的方式为对象建立索引;
  • get访问器返回值,set访问器分配值;
  • this关键字用于定义索引器;
  • 索引器不必根据整数值进行索引,可以自定义查找机制;
  • 索引器可被重载;
  • 索引器可以有多个行参;
  • 索引器必须是实例成员

简单示例

public class Indexer<T>
    {
        private T[] _arr=new T[100];
        public T this[int i]
        {
            get { return _arr[i]; }
            set { _arr[i] = value; }
        }
    }

简单示例

 public class Indexer<T>
    {
        string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };

        private int GetDay(string testDay)
        {

            for (int j = 0; j < days.Length; j++)
            {
                if (days[j] == testDay)
                {
                    return j;
                }
            }
            throw new System.ArgumentOutOfRangeException(testDay, "testDay must be in the form "Sun", "Mon", etc");
        }

        public int this[string day]
        {
            get
            {
                return (GetDay(day));
            }
        }
    }

C#索引器

C#索引器与属性之间的比较

原文地址:https://www.cnblogs.com/li-learning/p/CSharp_Index.html