c#编程指南(六) 类索引器(Class Indexer)

类索引器,可以使得你使用数组一样的方式来访问类的数据。

这种访问多见于数组,列表,词典,哈希表的快捷访问。

实际上写法很简单,写成:public T1 this[T2 i]

代码如下:

using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Drawing;

 namespace Indexer
{
    public class Test
    {
        private List<string> _lstTest = new List<string>();

        public List<string> Items 
        {
            get { return _lstTest; }
            set { _lstTest = value; }
        }

        public string this[int i]
        {
            get {
                if ((i >= 0) && (i < _lstTest.Count)) return _lstTest[i];
                else throw new IndexOutOfRangeException("the error index is " + i);
            }

            set {
                if ((i >= 0) && (i < _lstTest.Count)) _lstTest[i] = value;
                else throw new IndexOutOfRangeException("the error index is " + i);
            }
        }

        public string this[string s] { get { return "Test Return " + s; } }


        public string this[Color c] { get { return c.ToString(); } }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test();

            test.Items.Add("test1");
            test.Items.Add("test2");
            test.Items.Add("test3");
            for (int i = 0; i < test.Items.Count; i++)
            {
                Console.WriteLine(test[i]);
            }

            Console.WriteLine("----------------------------------------------------------");
            test[0] = "test4";
            for (int i = 0; i < test.Items.Count; i++)
            {
                Console.WriteLine(test[i]);
            }

            Console.WriteLine("----------------------------------------------------------");
            Console.WriteLine(test["香山飘雪"]);


            Console.WriteLine("----------------------------------------------------------");
            Console.WriteLine(test[Color.BlueViolet]);
        }
    }
}

很简单吧,

第一个,我定义了一个可读可写的以int为参数的索引器。

第二个,我定义了一个可读的以string为参数的索引器。

第三个,比较搞怪了,我定义了一个color参数的索引器。

原文地址:https://www.cnblogs.com/xbzhu/p/7381394.html