318

我想在一个类中添加一个运算符。我目前有一种GetValue()方法,我想用[]运算符替换。

class A
{
    private List<int> values = new List<int>();

    public int GetValue(int index) => values[index];
}
4

4 回答 4

822
public int this[int key]
{
    get => GetValue(key);
    set => SetValue(key, value);
}
于 2009-01-08T15:34:19.460 回答
68

我相信这就是您正在寻找的:

索引器(C# 编程指南)

class SampleCollection<T>
{
    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<string> stringCollection = 
            new SampleCollection<string>();
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}
于 2009-01-08T15:35:01.830 回答
33

[] 运算符称为索引器。您可以提供采用整数、字符串或您想用作键的任何其他类型的索引器。语法很简单,遵循与属性访问器相同的原则。

例如,在您的情况下 anint是键或索引:

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]
...
于 2009-01-08T15:39:38.233 回答
11
public int this[int index]
{
    get => values[index];
}
于 2009-01-08T15:35:03.657 回答