C# 使用属性从列表中获取值<;字符串>; private List_S3=new List(); 公共字符串S3[int索引] { 得到 { 返回S3[索引]; } }

C# 使用属性从列表中获取值<;字符串>; private List_S3=new List(); 公共字符串S3[int索引] { 得到 { 返回S3[索引]; } },c#,C#,唯一的问题是我犯了13个错误。我想调用string temp=S3[0]并从具有特定索引的列表中获取字符串值。尝试此操作 private List<string> _S3 = new List<string>(); public string S3[int index] { get { return _S3[index]; } } private List_S3=new List(); 公开名单S3 { 得到 { 返回S3; }

唯一的问题是我犯了13个错误。我想调用
string temp=S3[0]并从具有特定索引的列表中获取字符串值。

尝试此操作

private List<string> _S3 = new List<string>();
public string S3[int index]
{
    get
    {
        return _S3[index];
    }
}
private List_S3=new List();
公开名单S3
{
得到
{
返回S3;
}
}
在C#中不能这样做-在C#中不能有这样的命名索引器。您可以具有不带参数的命名属性,也可以具有带参数但不带名称的索引器

当然,您可以拥有一个名为的属性,该属性使用索引器返回一个值。例如,对于只读视图,可以使用:

private List<string> _S3 = new List<string>();
public List<string> S3
{
    get
    {
        return _S3;
    }
}
您可以在每次访问
S3
时创建一个新的
ReadOnlyCollection
,但这似乎有点毫无意义。

C#不能为其属性设置参数。(旁注:VB.Net也可以。)

您可以尝试改用函数:

string name = foo.S3[10];

你必须用这个符号

public string GetS3Value(int index) {
  return _S3[index];
}
我只想和你一起去

 public class Foo
    {
        public int this[int index]
        {
            get
            {
                return 0;
            }
            set
            {
                // use index and value to set the value somewhere.   
            }
        }
    }
类S3:列表{}

\u S3[i]应自动返回位置i处的字符串

所以,只要做:

class S3: List<string>{}

不,
\u S3
是私有的。创建属性的目的是从范围外的位置访问存储在
\u S3
中的值。这一点很好。我忽略了问题中的私人修饰语。然后你会想创建一个像LarsTech建议的公共方法。
class S3: List<string>{}
string temp = _S3[0];