C# 索引器

  索引器类似于属性。和属性相似,索引器一样有get和set访问器。

  索引器与属性的不同点:

  1、每个属性的名称必须唯一,而每一个索引器的签名必须唯一。

  2、索引器的“属性名”统一为this。而不能为其他,专门用于定义索引器。

  3、索引器的参数列表包含在方括号而不是圆括号之内。

  4、属性可以是静态的,而索引器只能为实例成员。

  5、属性的get访问器没有参数,而索引器的get访问器可以有参数,而且索引器的get访问器和set访问器的参数相同

  6、索引器可以有多个形参,比如访问多维数组时。

  索引器和数组对比:

              数组          索引器

  索引类型        整型,0-n        可以为任意类型

  是否存储数据      是           否,通过访问器操作存在其他地方的数据,例如集合或数组字符串等。

  是否允许重载      否            是,一个类可以有多个索引器

  代码示例1:

复制代码
class Program
    {
        static void Main(string[] args)
        {
            Index index = new Index();
            Console.WriteLine(index[1]);    //输出 刘备
            Console.WriteLine(index[2]);    //输出 关羽
            Console.WriteLine(index[3]);    //输出 张飞

            index[3] = "诸葛亮";
            Console.WriteLine(index[3]);    //输出 诸葛亮

            Console.ReadKey();
        }
    }

    public class Index
    {
        string Name1 = "刘备";
        string Name2 = "关羽";
        string Name3 = "张飞";

        public string this[int Id]
        {
            get
            {
                switch (Id)
                {
                    case 1:
                        return Name1;
                        break;
                    case 2:
                        return Name2;
                        break;
                    case 3:
                        return Name3;
                        break;
                    default:
                        return "";
                        break;
                }
            }
            set
            {
                switch (Id)
                {
                    case 1:
                        Name1 = value;
                        break;
                    case 2:
                        Name2 = value;
                        break;
                    case 3:
                        Name3 = value;
                        break;
                }
            }
        }
    }
复制代码

  代码示例2-字符串访问以及索引器的重载示例:

复制代码
    class Program
    {
        static void Main(string[] args)
        {
            Index index = new Index();;
            Console.WriteLine(index[0]);    //输出 刘备

            index.dic = new Dictionary<string, string>();
            index.dic.Add("诸葛亮","村夫");
            Console.WriteLine(index["诸葛亮"]);     //输出 村夫

            Console.ReadKey();
        }
    }

    public class Index
    {
        string[] strArr = { "刘备", "关羽", "张飞" };

        public string this[int i]
        {
            get
            {
                return strArr[i];
            }
            set
            {
                strArr[i] = value;
            }
        }

        public Dictionary<string, string> dic;
        public string this[string name]
        {
            get
            {
                return dic[name];
            }
            set
            {
                dic[name] = value;
            }
        }
    }
复制代码
原文地址:https://www.cnblogs.com/mingxuantongxue/p/3803719.html