2017-10-05 91 views
1

我有這個foreach循環,我試圖通過一個Table類的documentTables列表,其中包含包含Row類對象的Table對象。目前我收到一個錯誤:foreach語句不能對變量類型test1.Table進行操作,因爲它不包含GetEnumerator的公共定義。我沒有完全理解正在發生的事情,不確定實現接口的最佳方式是什麼。GetEnumerator接口實現

for (int i = 0; i < documentTables.Count(); i++) 
{ 
    foreach (Row r in documentTables[i]) 
    { 
     // some functionality here 
    } 
} 

表類(Row類幾乎相同,有幾根弦和構造函數):

class Table { 
public Row a; 
public Row b; 
public Row c; 

public Table (Row _a,Row _b,Row _c) 
{ 
a=_a; 
b=_b; 
c=_c; 

} 
} 
+0

如果你想要一個行,那麼你遍歷行,而不是在表上:_documentTables [i] .Rows; _ – Steve

+0

你必須顯示你的Table類,它是否實現'IEnumerable '或只是舉行一個集合,存儲行?在那種情況下,使用該屬性,如下所示:'foreach(row_in documentTables [i] .Rows)' –

+0

您是否已經實現了表格和行,而沒有它很難猜測 – duongthaiha

回答

1

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/foreach-in

foreach語句重複一組嵌入語句的每個 數組中的元素或實現 IEnumerableIEnumerable接口的對象集合中的元素。

所以你類需要實現IEnumerable的

class Table: IEnumerable 
{ 
    public Row a; 
    public Row b; 
    public Row c; 

    public Table(Row _a, Row _b, Row _c) 
    { 
     a = _a; 
     b = _b; 
     c = _c; 

    } 

    public IEnumerator GetEnumerator() 
    { 
     yield return a; 
     yield return b; 
     yield return c; 
    } 
} 


public class Row { } 

然後,你可以這樣做:

var myTable = new Table(new Row(), new Row(), new Row()); 
foreach (var row in myTable) 
{ 
    // some functionality here 
} 

另一種可能的實現你的表類的(更靈活,我認爲)如下:

class Table: IEnumerable 
{ 
    private Row[] _rows; 

    public Table(params Row[] rows) 
    { 
     this._rows = rows; 

    } 

    public IEnumerator GetEnumerator() 
    { 
     foreach (var row in _rows) 
     { 
      yield return row; 
     } 
    } 
} 

現在構造函數中的行數不限於三個。