c# - IEnumerator.MoveNext() 实现?

标签 c# interface ienumerable

我是 c# 的新手,我知道必须实现接口(interface)中定义的方法

但在下面的代码中我没有实现 MoveNext() 方法

static void Main()
{
    List<int> list = new List<int>();
    list.Add(1);
    list.Add(5);
    list.Add(9);

    List<int>.Enumerator e = list.GetEnumerator();
    Write(e);
}

static void Write(IEnumerator<int> e)
{
    while (e.MoveNext())
    {
        int value = e.Current;
        Console.WriteLine(value);
    }
}

我也检查了元数据,它没有提供任何实现。

那么为什么编译器没有抛出任何错误呢? MoveNext() 方法的实现在哪里 & 它如何移动到下一个值?

MoveNext() 方法的代码是否由编译器自动生成? 请帮忙

最佳答案

原因是,你没有实现IEnumerator<int> , 你用过 List<int>它已经实现并为 MoveNext 提供实现.

这是 actual implementation代码是:

public bool MoveNext() {

    List<T> localList = list;

    if (version == localList._version && ((uint)index < (uint)localList._size)) 
    {                                                     
        current = localList._items[index];                    
        index++;
        return true;
    }
    return MoveNextRare();
}

关于c# - IEnumerator.MoveNext() 实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29654411/

相关文章:

c# - 可以自动增加DLL版本

c# - 当线程区域性不是英语时,.NET CookieException "Cookie format error"- 仅在某些环境中

c# - 当我调用 NavigationService.Navigate() 时,Windows Phone 应用程序调用 MapUri() 两次

java - 在面向对象编程中,在其方法中引用接口(interface)子项是正确的方法吗?

c# - 使用自定义类转换 IEnumerable<dynamic>

c# - 链接 IEnumerable<T> 扩展方法的首选(性能和可读性)方式是什么?

c# - 是否可以使 IEnumerable<char> 实现 IComparable?

c# - 合并两个 XML 文件,文件具有一对多关系 C#

java - 当您同时具有虚拟和真实实现的接口(interface)时,单元测试的最佳方法是什么?

java - 实现一个调用接口(interface)方法的类?