2017-10-05 157 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; 
     } 
    } 
} 

现在构造函数中的行数不限于三个。