天天看點

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#