public int this[int key] { get => GetValue(key); set => SetValue(key, value); }
我相信这就是你要找的东西:
索引器(C#编程指南)
class SampleCollection{ private T[] arr = new T[100]; public T this[int i] { get => arr[i]; set => arr[i] = value; } } // This class shows how client code uses the indexer class Program { static void Main(string[] args) { SampleCollection stringCollection = new SampleCollection (); stringCollection[0] = "Hello, World"; System.Console.WriteLine(stringCollection[0]); } }
[]运算符称为索引器.您可以提供带整数,字符串或任何其他要用作键的类型的索引器.语法很简单,遵循与属性访问器相同的原则.
例如,在您的情况下,a int
是键或索引:
public int this[int index] { get => GetValue(index); }
您还可以添加set访问器,以便索引器变为读写,而不仅仅是只读.
public int this[int index] { get => GetValue(index); set => SetValue(index, value); }
如果要使用其他类型进行索引,只需更改索引器的签名即可.
public int this[string index] ...
public int this[int index] { get => values[index]; }