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

Ada*_*gen 285 c# indexer operator-overloading

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

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

    public int GetValue(int index) => values[index];
}
Run Code Online (Sandbox Code Playgroud)

Flo*_*her 724

public int this[int key]
{
    get => GetValue(key);
    set => SetValue(key, value);
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么每次我需要实现一个索引操作符时,我都要查找它?每次我最终得到这个答案...希望我可以多次投票:) (158认同)
  • 不知道为什么他们选择在这个宣言中省略"操作员"这个词 - 这就是我经常犯的错误!很好的答案 (16认同)
  • 这真是太棒了.可以在界面中完成吗?``interface ICache {object this [string key] {get; 组; ``编辑:**[是的.](http://stackoverflow.com/questions/9586625/how-to-define-indexer-behaviour-to-an-interface) (6认同)
  • 我只是想在将来打个招呼,他肯定会回到这里 (6认同)
  • 迈克尔:你应该使用泛型:`interface ICache <TContent> {TContent this [string key] {get; 组; }. (3认同)
  • 您还可以使用多维数组 `public int this[int x, int y]` (3认同)

Wil*_*del 64

我相信这就是你要找的东西:

索引器(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]);
    }
}
Run Code Online (Sandbox Code Playgroud)


Jef*_*tes 30

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

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

public int this[int index]
{
    get => GetValue(index);
}
Run Code Online (Sandbox Code Playgroud)

您还可以添加set访问器,以便索引器变为读写,而不仅仅是只读.

public int this[int index]
{
    get => GetValue(index);
    set => SetValue(index, value);
}
Run Code Online (Sandbox Code Playgroud)

如果要使用其他类型进行索引,只需更改索引器的签名即可.

public int this[string index]
...
Run Code Online (Sandbox Code Playgroud)


BFr*_*ree 9

public int this[int index]
{
    get => values[index];
}
Run Code Online (Sandbox Code Playgroud)