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

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

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

6个回答

7
在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>,但这似乎有点无意义。

2

C#的属性不能有参数。 (顺便说一句:VB.Net可以。)

您可以尝试使用函数代替:

public string GetS3Value(int index) {
  return _S3[index];
}

1
你必须使用这个符号表示
 public class Foo
    {
        public int this[int index]
        {
            get
            {
                return 0;
            }
            set
            {
                // use index and value to set the value somewhere.   
            }
        }
    }

0

_S3[i] 应该自动返回位置 i 上的字符串

所以只需要这样做:

string temp = _S3[0];

1
不,_S3私有的。创建属性的目的是从超出范围的地方访问存储在_S3中的值。 - Otiel
1
很好。我在问题中忽略了private修饰符。那么你需要像LarsTech建议的那样创建一个public方法。 - jmshapland

-1

试试这个

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

-1

我会选择

class S3: List<string>{}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接