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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/424669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 02:52:02  来源:igfitidea点击:

How do I overload the [] operator in C#

c#operator-overloadingindexer

提问by Adam Tegen

I would like to add an operator to a class. I currently have a GetValue()method that I would like to replace with an []operator.

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

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

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

采纳答案by Florian Greinacher

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

回答by William Brendel

I believe this is what you are looking for:

我相信这就是你要找的:

Indexers (C# Programming Guide)

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

回答by BFree

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

回答by Jeff Yates

The [] operator is called an indexer. You can provide indexers that take an integer, a string, or any other type you want to use as a key. The syntax is straightforward, following the same principles as property accessors.

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

For example, in your case where an intis the key or index:

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

public int this[int index]
{
    get => GetValue(index);
}

You can also add a set accessor so that the indexer becomes read and write rather than just read-only.

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

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

If you want to index using a different type, you just change the signature of the indexer.

如果要使用不同的类型进行索引,只需更改索引器的签名即可。

public int this[string index]
...