Why does foreach fail to find my GetEnumerator extension method?

前端 未结 8 1977
暗喜
暗喜 2021-02-18 21:19

I\'m trying to make some code more readable. For Example foreach(var row in table) {...} rather than foreach(DataRow row in table.Rows) {...}.

8条回答
  •  南方客
    南方客 (楼主)
    2021-02-18 21:31

    Within an foreach statement the compiler is looking for an instance method of GetEnumerator. Therefore the type (here DataTable) must implement IEnumerable. It will never find your extension method instead, because it is static. You have to write the name of your extension method in the foreach.

    namespace System.Data {
        public static class MyExtensions {
            public static IEnumerable GetEnumerator( this DataTable table ) {
                foreach ( DataRow r in table.Rows ) yield return r;
            }
        }
    }
    
    foreach(DataRow row in table.GetEnumerator())
      .....
    

    To avoid confusion, I would suggest using a different name for your extension method. Maybe something like GetRows()

提交回复
热议问题