3
有人可以解释一下索引器有什么好处吗?索引器有什么好处?
public class MyClass
{
private List<string> list = new List<string>()
public string this[int value]
{
get
{
return list[value];
}
}
public string GetValue(int value)
{
return list[value];
}
}
什么是使用的好处:
MyClass target = new MyClass();
string value = target[0];
在这个:
MyClass target = new MyClass();
string value = target.GetValue(0);
你不需要写'GetValue',你知道这个类是一个带有索引器的集合,但是你可能会失去可读性,因为索引器没有名字,所以不要误用它。 –
这是一个*语法糖*,优点是*可读性* –
@DmitryBychenko:可读性不是好处,反之亦然,因为索引器没有名字 –