Why does foreach fail to find my GetEnumerator extension method?

前端 未结 8 1996
暗喜
暗喜 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:51

    Your extension is equivalent to:

        public static IEnumerable<TDataRow> GetEnumerator<TDataRow>( this DataTable tbl ) {
            foreach ( TDataRow r in tbl.Rows ) yield return r;
        }
    

    GetEnumerator<TDataRow> is not the same method as GetEnumerator

    This will work better:

        public static IEnumerable<DataRow> GetEnumerator( this DataTable tbl ) {
            foreach (DataRow r in tbl.Rows ) yield return r;
        }
    
    0 讨论(0)
  • 2021-02-18 21:57

    The GetEnumerator method in your test class is not static, the extension method is. This doesn't compile either:

    class test
    {
    }
    
    static class x
    {
        public static IEnumerator<object> GetEnumerator(this test t) { return null; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            foreach (var i in new test()) {  }
        }
    }
    

    In order for the foreach syntax sugar to work your class must expose a public GetEnumerator instance method.

    Edit:

    As of C# 9.0, GetEnumerator can be an extension method.

    0 讨论(0)
提交回复
热议问题