天天看點

索引器

索引器是一個非常快速查找,指派的一個方法。

建立一個索引器是一個簡單的過程。

索引器和屬性有同樣的get和set。用法也是一樣的

不過在索引器的建立的時候,要注意必須要傳回值和this關鍵字【對應着執行個體化的類】

索引器不限制重載

索引器不限參數數量

索引器不限制傳回值類型但必須有

public class TestIndex
    {
        private int [] id;        
        public TestIndex(int n) => id = new int[n]; 
        public int this[int index]
        {       
            get
            {
                if (index <= id.Length)
                    return id[index];
                return int.MinValue;
            }
            set
            {
                if (index < id.Length)
                    id[index] = value;
            }          
        }
        public int [] this[int from,int to]
        {
            get
            {
                int[] reulst=null;
                if (from < id.Length && from >= 0 && to < id.Length && to >= 0)
                {
                    if (from == to)
                        return new int[] { id[from] };

                    reulst = new int[to - from];

                    while (from < to)
                    {
                        reulst[from] = id[from];
                        from++;
                    }
                }
                return reulst;
            }
        }
    }
    class Program      

測試

class Program
    {
        static void Main(string[] args)
        {
            var test = new TestIndex(5);
            test[0] = 10;
            test[1] = 20;
            test[2] = 30;
            var ten = test[0];
            Console.WriteLine(ten);
            //輸出10
            var array = test[0, 2];
            foreach (var item in array)
                Console.WriteLine($"{item}");
            //輸出10 20 
        }
    }