Enumerable.Range implementation

后端 未结 4 1636
失恋的感觉
失恋的感觉 2020-12-20 08:21

What is the precise implementation of Enumerable.Range in .Net; preferable .Net 4? Is it a yielded for-loop? A custom implementation (IEnumerable, IEnumerator) or?<

相关标签:
4条回答
  • 2020-12-20 08:49

    The accepted answer on this question should give you the answer:

    public static class Enumerable {
        public static IEnumerable<int> Range(int start, int count) {
            var end = start + count;
            for(var current = start; current < end; ++current) {
                yield return current;
            }
        }
    }
    

    This isn't the exact code, as there is a lot of error checking etc. going on within the Range method, and internally, it calls other methods, however, the quoted code above is the "essence" of the Range routine.

    Examining the code in Reflector should provide you with far more information.

    0 讨论(0)
  • 2020-12-20 08:54

    You can use Reflector to see the implementation for yourself. It checks arguments and throws exception at the time of calling, so the Range method itself is not an iterator method. It calls another method which is an iterator method. It's not OK to post the exact code due to license restrictions.

    0 讨论(0)
  • 2020-12-20 09:12

    .NET 4

    In February 2014, Microsoft put a .NET Source Code browser online. Thus, your question can now be answered with an offical source:

    Enumerable.Range uses a custom iterator.

    The license still does not allow posting the code here, but you can look at it yourself at this link:

    • https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,fda9d378095a6464

    .NET Core

    .NET Core is licensed under the more permissive MIT license. I am not a lawyer, so I don't know if this means I may copy-and-paste it to StackOverflow or not, but here is the direct link to their Enumerable.Range implementation:

    • https://github.com/dotnet/corefx/blob/143df51926f2ad397fef9c9ca7ede88e2721e801/src/System.Linq/src/System/Linq/Range.cs
    0 讨论(0)
  • 2020-12-20 09:13

    A slight but significant difference in the Reflector output (as well as the argument check and extra level of internalisation mentioned in CraigTP's answer and its comments):

    public static IEnumerable<int> Range(int start, int count) {
        for(int current = 0; current < count; ++current) {
            yield return start + current;
        }
    }
    

    That is, instead of another local variable, they apply an extra addition for every yield.

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