Can we use GetEnumerator() without using IEnumerable interface?

我与影子孤独终老i 提交于 2019-11-30 19:25:35

问题


I have a class called Primes and this class implements GetEnumerator() without implementing IEnumerable interface.

public class Primes
{
    private long min;
    private long max;

    public Primes()
        : this(2, 100)
    {
    }

    public IEnumerator GetEnumerator()
    {...}

I don't get it. Am I missing something?


回答1:


Firstly, as others have said you can introduce your own methods without implementing interfaces anyway - you can write your own Dispose method without implementing IDisposable etc. For well-known interfaces I'd suggest this is almost a bad idea (as readers will have certain expectations) but it's entirely valid.

More importantly though, the foreach statement in C# can work without IEnumerable being involved. The compiler effectively does compile-time duck typing on the names GetEnumerator(), Current and MoveNext(). This was primarily to allow strongly-typed (and non-boxing) iteration in C# 1, before generics. See section 8.8.4 of the C# 3 spec for more details.

However, it's generally a bad idea to do this now if you do want to be able to easily iterate over the contents of an instance as a collection - and indeed I'd suggest implementing IEnumerable<T> instead of just IEnumerable.




回答2:


yes you can. even you can use it in foreach. The only problem that objects of this class can't be cast to IEnumerable although they implement needed method.




回答3:


There's no reason that you have to implement IEnumerable in order to create a function called GetEnumerator that returns an IEnumerator, that just means that you won't be able to supply an instance of that type to something that expects an IEnumerable.




回答4:


an interface ensures a contract, that does not mean that you can't have a method with the same signature as one in the interface on a class that does not impliment the interface.



来源:https://stackoverflow.com/questions/2905737/can-we-use-getenumerator-without-using-ienumerable-interface

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!