c# - 使用 Property 从 List<string> 获取值

标签 c#

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/

相关文章:

javascript - javascript 上的预期十六进制

c# - 如何验证一个事件已经被模拟取消订阅

c# - 操纵杆键捕获

C# 创建目录并设置权限

c# - 为什么 Visual Studio 2010 在调试重启时重新编译我的 C# 项目?

c# - 在 try catch block 中对 IDisposable 使用 block 是否有任何问题?

c# - 如何使用服务器端将数据发布到 MVC4 中的外部 URL

c# - 如何在C#中将巨大的JSON文件转换为xml文件

c# - WPF Datagrid 排序索引问题

c# - 取消对 'HttpClient.SendAsync()' 的调用