List<T>.Enumerator 怎么没有按照其接口的要求实现 Reset?
How does List<T>.Enumerator not implement Reset as required by its interface?
在实现我自己的 collection 时,我通过将所有 objects 复制到一个列表中来模拟枚举器,然后将所有枚举器调用重定向到我存储引用的列表的枚举器。但是当 List.Enumerator 没有 Reset 方法时,我 运行 遇到了问题;尽管它实现了 IEnumerator.
以下是反映的 headers 问题(删除了注释)
public class List<T> : IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
{
public struct Enumerator : IEnumerator<T>, IDisposable, IEnumerator
{
public T Current { get; }
public void Dispose();
public bool MoveNext();
}
}
public interface IEnumerator<out T> : IDisposable, IEnumerator
{
T Current { get; }
}
public interface IEnumerator
{
object Current { get; }
bool MoveNext();
void Reset();
}
这里我们可以看到List.Enumerator两次派生自IEnumerator;首先显式,然后通过 IEnumerator 隐式。但是这个示例程序不会编译。
List<int> list = new List<int>();
List<int>.Enumerator enumerator = list.GetEnumerator();
enumerator.Reset();
Error CS1061 'List.Enumerator' does not contain a definition for 'Reset' and no extension method 'Reset' accepting a first argument of type 'List.Enumerator' could be found (are you missing a using directive or an assembly reference?)
List.Enumerator 怎么可能没有 implement/expose 在其接口之一中声明的方法?
Reset
方法是通过显式接口实现实现的。参见:https://source.dot.net/#System.Private.CoreLib/shared/System/Collections/Generic/List.cs,1141
因此,它不是 List<T>.Enumerator
的 public 成员
在实现我自己的 collection 时,我通过将所有 objects 复制到一个列表中来模拟枚举器,然后将所有枚举器调用重定向到我存储引用的列表的枚举器。但是当 List.Enumerator 没有 Reset 方法时,我 运行 遇到了问题;尽管它实现了 IEnumerator.
以下是反映的 headers 问题(删除了注释)
public class List<T> : IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
{
public struct Enumerator : IEnumerator<T>, IDisposable, IEnumerator
{
public T Current { get; }
public void Dispose();
public bool MoveNext();
}
}
public interface IEnumerator<out T> : IDisposable, IEnumerator
{
T Current { get; }
}
public interface IEnumerator
{
object Current { get; }
bool MoveNext();
void Reset();
}
这里我们可以看到List.Enumerator两次派生自IEnumerator;首先显式,然后通过 IEnumerator 隐式。但是这个示例程序不会编译。
List<int> list = new List<int>();
List<int>.Enumerator enumerator = list.GetEnumerator();
enumerator.Reset();
Error CS1061 'List.Enumerator' does not contain a definition for 'Reset' and no extension method 'Reset' accepting a first argument of type 'List.Enumerator' could be found (are you missing a using directive or an assembly reference?)
List.Enumerator 怎么可能没有 implement/expose 在其接口之一中声明的方法?
Reset
方法是通过显式接口实现实现的。参见:https://source.dot.net/#System.Private.CoreLib/shared/System/Collections/Generic/List.cs,1141
因此,它不是 List<T>.Enumerator