我想给一个类添加一个操作符。目前我有一个GetValue()
方法,我想用一个[]
运算符来替换它。
class A
{
private List<int> values = new List<int>();
public int GetValue(int index) => values[index];
}
我想给一个类添加一个操作符。目前我有一个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);
}
我相信这是你在寻找的内容:
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]);
}
}
[]运算符称为索引器。您可以提供索引器,接受整数、字符串或任何其他类型的键。语法很简单,遵循与属性访问器相同的原则。
例如,在您的情况下,其中一个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]
...
public int this[int index]
{
get => values[index];
}
接口ICache{ object this[string key] { get; set; } }
编辑: 是的。 - Michaelinterface ICache<TContent> { TContent this[string key] { get; set; } }
。 - cemper93public int this[int x, int y]
。 - Paul Baxter