When I emplement IEnumerable<T>
interface I see two GetEnumerator
methods: one returning IEnumerator
and other IEnumerator<T>
. When would I use one or another?
相关问题
- Implementing multiple IEnumerables in C#
- What interface to I need to implement to allow For
- Easiest method to OrderBy a String using StringCom
-
How do I correctly wrap a Dictionary
and expose - How does foreach casts objects to specified types?
相关文章
-
IEnumerable
vs IReadOnlyList - Serializing result of a LINQ IEnumerable
- Converting an array of type T to an array of type
- Count an IOrderedEnumerable without consuming it
- What is the difference between IEnumerable and arr
- How does the RemoveRange() method work in a List&l
- Modelbinding IEnumerable in ASP.NET MVC POST?
- Split C# collection into equal parts, maintaining
If you are implementing the
IEnumerable<T>
generic interface, you will pretty much always have to use the generic GetEnumerator method - unless you cast your object explicitly to (non-generic) IEnumerable.The reason is backwards compatability with .NET 1.0/1.1 which didn't support generics.
You usually implement both. One is the newer, generic version that returns a typesafe enumerator (
IEnumerator<T>
). The other one is for compatibility with Legacy code (returnsIEnumerator
). A typical implementation is:Usually
GetEnumerator()
callsGetEnumerator<T>()
, so there should not be much difference in behavior. As for why there are two methods, this is done for backwards compatibility and for use in situation whereT
is not of great interest (or is just unknown).The reason there are two methods is because
IEnumerable<T>
inherits theIEnumerable
interface so you are seeing the generic method fromIEnumerable<T>
and the non-generic method fromIEnumerable
.Here is how you want to implement the interface in your type:
The one is generic, the other one not. I believe the compiler prefers to use the generic overload.