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

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

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

public int this[int key]
{
    get => GetValue(key);
    set => SetValue(key, value);
}

我相信这就是你想要的:

索引器(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]);
    }
}
public int this[int index]
{
    get => values[index];
}

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

例如,在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]
...