private List<string> _S3 = new List<string>();
public string S3[int index]
{
get
{
return _S3[index];
}
}
唯一的问题是我遇到了 13 个错误。我想调用 string temp = S3[0];
并从具有特定索引的列表中获取字符串值。
最佳答案
您不能在 C# 中执行此操作 - 您不能在 C# 中使用这样的命名索引器。您可以有一个没有参数的命名属性,或者您可以有一个有参数但没有名称的索引器。
当然,您可以拥有一个属性,该属性的名称返回带有索引器的值。例如,对于只读 View ,您可以使用:
private readonly List<string> _S3 = new List<string>();
// You'll need to initialize this in your constructor, as
// _S3View = new ReadOnlyCollection<string>(_S3);
private readonly ReadOnlyCollection<string> _S3View;
// TODO: Document that this is read-only, and the circumstances under
// which the underlying collection will change
public IList<string> S3
{
get { return _S3View; }
}
这样底层集合从公共(public)角度来看仍然是只读的,但您可以使用以下方式访问元素:
string name = foo.S3[10];
您可以创建一个新的 ReadOnlyCollection<string>
每次访问 S3
,但这似乎有点毫无意义。
关于c# - 使用 Property 从 List<string> 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8190670/