如何在C#中重载[]运算符

330

我想给一个类添加一个操作符。目前我有一个GetValue()方法,我想用一个[]运算符来替换它。

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

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

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

196
为什么每次我需要实现一个索引运算符时,都要去查阅资料?然后每次都会找到这个答案……真希望我能投多次赞 :) - dso
7
这太棒了,它能在一个接口中完成吗?接口ICache{ object this[string key] { get; set; } } 编辑: 是的。 - Michael
22
不知道为什么他们在这个声明中选择省略“operator”这个词——这是我经常犯的错误!答案不错。 - JonnyRaa
5
Michael建议使用泛型:interface ICache<TContent> { TContent this[string key] { get; set; } } - cemper93
3
你也可以使用多维数组 public int this[int x, int y] - Paul Baxter

69

我相信这是你在寻找的内容:

索引器(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]);
    }
}

34

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

例如,在您的情况下,其中一个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]
...

不要忘记,您可以为多个索引器使用任何类型的组合... - DrPhill

12
public int this[int index]
{
    get => values[index];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接