private List<string> _S3 = new List<string>();
public string S3[int index]
{
get
{
return _S3[index];
}
}
唯一的問題是我得到13個錯誤。我想調用string temp = S3[0];
並從列表中獲取具有特定索引的字符串值。使用屬性從列表中獲取價值<string>
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];
你可能創建一個新的ReadOnlyCollection<string>
每個訪問S3
,但這似乎有點毫無意義。
試試這個
private List<string> _S3 = new List<string>();
public List<string> S3
{
get
{
return _S3;
}
}
暴露一個ICollection的
C#不能有它們的屬性的參數。 (附註:VB.Net雖然可以。)
您可以嘗試使用一個函數:
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];
不,'_S3'是*私人*。創建屬性的要點是從超出範圍的地方訪問存儲在_S3中的值。 – Otiel
好點。我忽略了問題中的私人修飾語。 然後你想創建一個像LarsTech建議的公共方法。 – jmshapland
什麼是錯誤 –