使用属性从列表中获取值

本文关键字:获取 string 属性 列表 | 更新日期: 2023-09-27 18:15:05

private List<string> _S3 = new List<string>();
public string S3[int index]
{
    get
    {
        return _S3[index];
    }
}

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

使用属性从列表<string>中获取值

你不能在c#中这样做——你不能像在c#中那样命名索引器。你可以有一个命名属性,没有参数,你可以有一个有参数但没有名称的索引器。

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

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; }
}

这样,从公共角度来看,底层集合仍然是只读的,但是您可以使用:

访问元素。
string name = foo.S3[10];

可以在每次访问S3时创建一个新的ReadOnlyCollection<string>,但这似乎有点无意义。

c#不能为其属性设置参数。(旁注:VB。)

你可以试试用函数代替:

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[i]应该自动返回位置i的字符串

那么就这样做:

string temp = _S3[0];

试试这个

private List<string> _S3 = new List<string>();
public List<string> S3
{
    get
    {
        return _S3;
    }
}

我就用

class S3: List<string>{}