Multiple IEnumerable implementations paradox

前端 未结 2 1051
梦谈多话
梦谈多话 2021-01-18 23:56
  1. I have a generic class A<T>, that implements IEnumerable<T[]>.
  2. I want to have a convenience wrapper B that inherits from A<c

相关标签:
2条回答
  • 2021-01-19 00:30

    The difference is the following:

    foreach actually looks for a public method called GetEnumerator. It doesn't really care for IEnumerable<T>. Your class B only has one public method named GetEnumerator: The one defined in B which hides the one defined in A.

    ToArray on the other hand is an extension method on IEnumerable<T>. As your class is both IEnumerable<string> and IEnumerable<char[]> the call is ambiguous between the two generic arguments string and char[].

    0 讨论(0)
  • 2021-01-19 00:53

    foreach loop does not use IEnumerable or IEnumerable<T> implementation. You can use foreach even if your class doesn't implement any of them. The only thing it needs is GetEnumerator method that returns IEnumerator implementation.

    Check this question: How is foreach implemented in C#?

    That's why your class works with foreach and doesn't with ToArray().

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