C# 索引器

1.说明

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

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

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

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

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

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

  • 索引器可被重载。

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

2.示例代码

namespace CSharpDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            StudentScore sc = new StudentScore();
            Console.WriteLine("第一位学生的成绩是{0}分", sc[0]);

            Console.ReadLine();
        }
    }


    /// <summary>
    /// 索引器示例
    /// </summary>
    public class StudentScore
    {
        private double[] sc = { 90, 88, 67, 41, 67, 72, 98 };
        private string[] names = { "Li", "Xu", "Zhang", "Wang", "Chen", "Wu", "Hu" };

        public double this[int i]
        {
            get
            {
                return sc[i];
            }
            set
            {
                sc[i] = value;
            }
        }

        //可以有多个索引器只有参数不同就可以
        public string this[string name]
        {
            get
            {
                return GetName(name);
            }
        }

        private string GetName(string name)
        {
            foreach (string s in names)
            {
                if (s == name)
                {
                    return s;
                }
            }

            return string.Empty;
        }
    }
}
原文地址:https://www.cnblogs.com/xqhppt/p/2315770.html