C#實現索引器

引言

索引器是一種特殊的方法,為類提供對象[下標]訪問內容的方式.

語法


class 類名 {

      其他字段,屬性,方法等......
      
      public 返回值類型 this[索引值類型 索引] {
            定義訪問方式
      }
}

例子:

using System;

namespace LearnClass {
    class Program {
        static void Main (string[] args) {
            Test t = new Test();
            t[8] = -12;
            for ( int i = 1; i < 11; i++ ) {
                Console.WriteLine(t[i]);
            }
        }

    }
    class Test {
        int[] arr = new int[10];
        public Test() {
            for(int i = 0; i < 10; i++) {
                arr[i] = i;
            }
        }
        public int this[int index] {
            get => arr[index - 1];
            set => arr[index - 1] = value;
        }
    }
}

輸出結果:

原文地址:https://www.cnblogs.com/ltozvxe/p/13975192.html