[英]Does foreach prefer IEnumerable<T> or IEnumerator<T>
如果集合或列表同时实现IEnumerable <T>和IEnumerator <T>,foreach会使用什么?
IEnumerable<T>
有一个方法GetEnumerator
- 这将是一个IEnumerator<T>
,它是用于迭代的(使用MoveNext
方法)。
You can't use a foreach
on an IEnumerator<T>
at all. 你根本不能在
IEnumerator<T>
上使用foreach
。
You can only foreach
over an object that has a GetEnumerator
method (whether or not it implements IEnumerable
. 您只能
foreach
在具有对象GetEnumerator
方法(无论它实现IEnumerable
。
So to answer your question, it uses the GetEnumerator
method from IEnumerable<T>
. 所以要回答你的问题,它使用
IEnumerable<T>
的GetEnumerator
方法。
It's simple to prove. 这很容易证明。 Just try to compile this:
试着编译一下:
IEnumerator<char> str = "asdf".GetEnumerator();
foreach (char c in str) { }
Also notice, that this is not a requirement for collection to implement IEnumerable/IEnumerator in order be used in foreach loop. 另请注意,这不是集合实现IEnumerable / IEnumerator以便在foreach循环中使用的要求。 Foreach uses pattern-based approach as described here Eric Lippert blog
Foreach使用基于模式的方法,如Eric Lippert博客所述
Another (more relevant) question would be: What if a type implements IEnumerable<>
explicitly and at the same time has a regular public method GetEnumerator()
that is suitable? 另一个(更相关的)问题是:如果一个类型明确地实现
IEnumerable<>
并且同时具有适合的常规公共方法GetEnumerator()
,该怎么办? Answer: Then the public method is used. 答案:然后使用公共方法。
And what if the type implements both IEnumerable<Foo>
and IEnumerable<Bar>
? 而如果该类型实现了两者
IEnumerable<Foo>
和 IEnumerable<Bar>
? Then, if there's not a regular instance method GetEnumerator()
(that can happen if both interfaces are implemented explicitly), a compile-time error arises. 然后,如果没有常规实例方法
GetEnumerator()
(如果两个接口都是显式实现的话,就会发生这种情况),就会出现编译时错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.