如何在 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
How do I overload the [] operator in C#
提问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)
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 int
is 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]
...