我正在尝试使一些代码更具可读性。例如foreach(var row in table) {...}
,而不是foreach(DataRow row in table.Rows) {...}
.
为此,我创建了一个扩展方法:
namespace System.Data {
public static class MyExtensions {
public static IEnumerable<DataRow> GetEnumerator( this DataTable tbl ) {
foreach ( DataRow r in tbl.Rows ) yield return r;
}
}
}
但编译器仍然抛出foreach statement cannot operate on variables of type 'System.Data.DataTable' because 'System.Data.DataTable' does not contain a public definition for 'GetEnumerator'
.
为了确认我正确地实现了扩展方法,我尝试了以下代码,编译器没有问题。
for ( IEnumerator<DataRow> enm = data.GetEnumerator(); enm.MoveNext(); ) {
var row = enm.Current;
...
}
在您说这是因为IEnumerator
还是IEnumerator<DataRow>
未实现之前,请考虑以下内容确实可以编译:
public class test {
public void testMethod() {
foreach ( var i in new MyList( 1, 'a', this ) ) { }
}
}
public class MyList {
private object[] _list;
public MyList( params object[] list ) { _list = list; }
public IEnumerator<object> GetEnumerator() { foreach ( var o in _list ) yield return o; }
}