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)
Wil*_*del 64
我相信这就是你要找的东西:
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)
| 归档时间: |
|
| 查看次数: |
127718 次 |
| 最近记录: |