我们可以使用的GetEnumerator()不使用IEnumerable接口? [英] Can we use GetEnumerator() without using IEnumerable interface?

查看:293
本文介绍了我们可以使用的GetEnumerator()不使用IEnumerable接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个叫素数和这个类没有实现IEnumerable接口实现的GetEnumerator()。

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?

推荐答案

首先,正如其他人所说,你可以引入不反正实现接口你自己的方法 - 你可以写没有实现自己的的Dispose 方法的IDisposable 等驰名接口我建议这几乎是一个坏主意(如读者有一定的预期),但它是完全有效的。

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.

更重要的是,在的foreach 在C#声明的可以的不的IEnumerable 工作被卷入。编译器有效地做编译时间上的名字鸭键入的GetEnumerator()电流的MoveNext()。这主要是让在C#1强类型(和非拳击)迭代,仿制药之前。看到C#3规范第8.8.4更多的细节。

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.

然而,这通常是一个坏主意,现在这样做,如果你的的希望能够轻松地遍历实例作为集合的内容 - 事实上我建议实施的IEnumerable< T> ,而不是仅仅的IEnumerable

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.

这篇关于我们可以使用的GetEnumerator()不使用IEnumerable接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆