Why does foreach fail to find my GetEnumerator extension method?

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

    This will be possible in C# 9. The proposal is already checked in. You can verify in Language Feature Status - C# 9 when it will become available in a preview version.

    In the detailed design section of the proposal, it says:

    Otherwise, determine whether the type 'X' has an appropriate GetEnumerator extension method

    using System;
    using System.Collections.Generic;
    
    public static class MyExtensions
    {
        // Note: ranges aren't intended to work like this. It's just an example.
        public static IEnumerable GetEnumerator(this Range range)
        {
            // .. do validation ..
            for (var i = range.Start.Value; i <= range.End.Value; i++)
            {
                yield return i;
            }
        }
    }
    
    public class ExtensionGetEnumerator
    {
    
        public void Method()
        {
            var range = 1..2;
            foreach (var i in range.GetEnumerator())
            {
                Console.WriteLine($"Print with explicit GetEnumerator {i}");
            }
    
            // The feature is in progress, scheduled for C# 9, the below does not compile yet
    
            //foreach (var i in range)
            //{
            //    Console.WriteLine($"Print with implicit GetEnumerator {i}");
            //}
        }
    }
    

提交回复
热议问题