GetEnumerator接口实现

GetEnumerator interface implementation

我有这个 foreach 循环,我试图通过一个文档Table 的 Table class 列表,其中包含 Table 个对象,其中包含 Row class 对象。目前我收到一条错误消息:foreach 语句无法对 test1.Table 类型的变量进行操作,因为它不包含 GetEnumerator 的 public 定义。我不完全理解发生了什么,也不确定实现接口的最佳方式是什么。

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

TABLE CLASS(第 class 行几乎相同,几乎没有字符串和构造函数):

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;

} 
}

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

The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the IEnumerable or IEnumerable interface.

所以你的Tableclass需要实现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
}

您的 Table class 的另一种可能实现方式(我认为更灵活)如下:

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;
        }
    }
}

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