2011-11-19 73 views
3
private List<string> _S3 = new List<string>(); 
public string S3[int index] 
{ 
    get 
    { 
     return _S3[index]; 
    } 
} 

唯一的問題是我得到13個錯誤。我想調用string temp = S3[0];並從列表中獲取具有特定索引的字符串值。使用屬性從列表中獲取價值<string>

+0

什麼是錯誤 –

回答

7

你不能這樣做,在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,但這似乎有點毫無意義。

-1

試試這個

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

暴露一個ICollection的但沒有列表...請... – m0sa

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. 
      } 
     } 
    } 
-1

我只想與

class S3: List<string>{} 
+0

爲什麼要創建一個類? – Otiel

0

_S3 [i]應自動返回位置i的字符串

所以只是做:

string temp = _S3[0]; 
+1

不,'_S3'是*私人*。創建屬性的要點是從超出範圍的地方訪問存儲在_S3中的值。 – Otiel

+1

好點。我忽略了問題中的私人修飾語。 然後你想創建一個像LarsTech建議的公共方法。 – jmshapland