【发布时间】:2011-02-23 16:49:51
【问题描述】:
我有一个名为Rows 的自定义类,它实现了IEnumerable<Row>。我经常在 Rows 实例上使用 LINQ 查询:
Rows rows = new Rows { row1, row2, row3 };
IEnumerable<Row> particularRows = rows.Where<Row>(row => condition);
我希望能够做到以下几点:
Rows rows = new Rows { row1, row2, row3 };
Rows particularRows = (Rows)rows.Where<Row>(row => condition);
但是,我收到“System.InvalidCastException:无法将 'WhereEnumerableIterator1[NS.Row]' 类型的对象转换为 'NS.Rows' 类型”。我确实有一个Rows 构造函数采用IEnumerable<Row>,所以我可以这样做:
Rows rows = new Rows { row1, row2, row3 };
Rows particularRows = new Rows(rows.Where<Row>(row => condition));
然而,这看起来很庞大,我希望能够将IEnumerable<Row> 转换为Rows,因为Rows 实现了IEnumerable<Row>。有什么想法吗?
【问题讨论】:
-
只是一个备注(与您的问题无关):您不需要为
Where指定泛型类型参数,它是由编译器自动推断的 -
@Thomas:我实际上有几个不同的继承类,它们实现了不同的泛型
IEnumerable<T>,所以泛型类型参数需要在我的真实代码中。我这里显示的示例不需要它,你是对的。
标签: c# linq inheritance interface casting