Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/275.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/visual-studio/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# GetEnumerator接口实现_C#_Foreach_Interface_Enumerator - Fatal编程技术网

C# GetEnumerator接口实现

C# GetEnumerator接口实现,c#,foreach,interface,enumerator,C#,Foreach,Interface,Enumerator,我有一个foreach循环,我试图遍历一个documentTables表类列表,其中包含表对象,表对象包含行类对象。目前,我收到一个错误消息:foreach语句无法对test1.Table类型的变量进行操作,因为它不包含GetEnumerator的公共定义。我不完全理解正在发生的事情,也不确定实现接口的最佳方式是什么 for (int i = 0; i < documentTables.Count(); i++) { foreach (Row r in documentTables[

我有一个foreach循环,我试图遍历一个documentTables表类列表,其中包含表对象,表对象包含行类对象。目前,我收到一个错误消息:foreach语句无法对test1.Table类型的变量进行操作,因为它不包含GetEnumerator的公共定义。我不完全理解正在发生的事情,也不确定实现接口的最佳方式是什么

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

foreach语句为每个对象重复一组嵌入语句 元素,该元素位于实现 或接口

因此,您的Table类需要实现IEnumerable:

然后你可以做:

var myTable = new Table(new Row(), new Row(), new Row());
foreach (var row in myTable)
{
    // some functionality here
}
Table类的另一个可能实现(我认为更灵活)如下所示:

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

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

如果需要行,则可以在行上循环,而不是在表上循环:documentTables[i]。行;您必须显示您的表类,它是实现了
IEnumerable
还是只保存一个存储行的集合?在这种情况下,使用该属性,f.e.:
foreach(documentTables[i]中的r行)。Rows)
是否有表和行的实现,如果没有它,则很难进行二次猜测来说明
table
是如何实现的。@Sweeper table类只有行变量和构造函数
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;
        }
    }
}