天天看点

C# 索引器(Indexer) this关键字的作用

索引器使你可从语法上方便地创建类、结构或接口,以便客户端应用程序能像访问数组一样访问它们。 在主要目标是封装内部集合或数组的类型中,常常要实现索引器。

话不多说,直接上代码

//现在要创建一个类,People,我想像用数组一样创建它People[]。

    class People
    {
        public string name;
        public int age;

        public People(string name,int age)
        {
            this.name = name;
            this.age = age; 
        }

        //以下是索引器的代码
        public People this[int i]
        {
            get { return this[i]; }
            set { this[i] = value; }
        }

        //也可以这样写
        //public People this[int i]
        //{
        //    get => this[i];
        //    set => this[i] = value;
        //}
    }
           
class Program
    {
        static void Main(string[] args)
        {
            People[] peoples = new People[10];
            peoples[0] = new People("Link", 18);
            peoples[1] = new People("Zelda", 118);

            Console.WriteLine($"Name:{peoples[0].name},Age:{peoples[0].age}");
            Console.WriteLine($"Name:{peoples[1].name},Age:{peoples[1].age}");
            Console.ReadKey();
        }
    }
           

最后输出结果:

Name:Link,Age:18

Name:Zelda,Age:118

我刚才举的例子在实际中并不常始用,反倒是这样的情况比较多。我现在有一个类叫做名册,里面有string[]  names存着不同学生的名字,现在要获取这个类的对象的string[]  names数组中的这些名字,我通常是这样的mingce.names[i] 来获取。其实这里使用索引器就很好,可以mingce[i]这样来获取。

一个例子

class Mingce
    {
        public string[] names = new string[3] { "牧之原翔子", "樱岛麻衣", "双叶理央" };
        
        public int Length
        {
            get { return names.Length; }
        }

        public string this[int i]=>names[i]; //声明索引器
    }


class Program
    {
        static void Main(string[] args)
        {
            Mingce mingce = new Mingce();
            Console.WriteLine($"名字:{mingce[0]}");
            Console.WriteLine($"名字:{mingce[1]}");
            Console.WriteLine($"名字:{mingce[2]}");
            
            Console.WriteLine($"名字:{mingce.names[0]}");
            Console.WriteLine($"名字:{mingce.names[1]}");
            Console.WriteLine($"名字:{mingce.names[2]}");

            Console.ReadKey();
        }
    }
           

除了可以以int值作为索引外,还可以是string的类型。并且可以this[int i , int j]这样构建二维数组。具体可以自己尝试。

参考资料:https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/indexers/index

c#