1. 程式人生 > 實用技巧 >c# 索引器(Dictionary賦值取值的方式)

c# 索引器(Dictionary賦值取值的方式)

1. 什麼是索引器?

  索引器提供了一種訪問類或者結構的方法,即允許按照與陣列相同的方式對類、結構或介面進行索引。

  例如:Dictionary(詞典類)的賦值取值方式。

2.數字索引器

  2.1定義一個索引器類

    public class University
    {
        private const int MAX = 10;
        private string[] names = new string[MAX];

        //索引器
        public string this[int index]
        {
            get
            {
                if(index >= 0 && index < MAX)
                {
                    return names[index];
                }
                return null;
            }
            set
            {
                if (index >= 0 && index < MAX)
                {
                    names[index] = value;
                }
            }
        }
    }

  2.2使用這個索引器類

            University u = new University();
            u[0] = "測試大學0";
            u[1] = "測試大學1";
            u[2] = "測試大學2";
            System.Console.WriteLine(u[0]);
            System.Console.WriteLine(u[1]);
            System.Console.WriteLine(u[2]);

  2.3話白

  是不是很像Dictionary(詞典類)的賦值取值方式了?但這隻能用數字來索引;

3.字串索引器

  3.1定義一個索引器類

  3.2使用這個索引器類

  3.3話白