我们可以在不使用 IEnumerable 接口的情况下使用 GetEnumerator() 吗?
我有一个名为 Primes 的类,该类实现 GetEnumerator() 而不实现 IEnumerable 接口。
public class Primes
{
private long min;
private long max;
public Primes()
: this(2, 100)
{
}
public IEnumerator 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,正如其他人所说,您可以在不实现接口的情况下引入自己的方法 - 您可以编写自己的
Dispose
方法而不实现IDisposable
等。对于众所周知的接口,我'我认为这几乎是一个坏主意(因为读者会有一定的期望),但它是完全有效的。但更重要的是,C# 中的
foreach
语句可以在不涉及IEnumerable
的情况下工作。编译器有效地对名称GetEnumerator()
、Current
和MoveNext()
执行编译时鸭子类型。这主要是为了在泛型之前允许 C# 1 中的强类型(和非装箱)迭代。有关更多详细信息,请参阅 C# 3 规范的第 8.8.4 节。然而,如果您希望能够轻松地将实例的内容作为集合进行迭代,那么现在这样做通常是一个坏主意 - 事实上,我建议实现
IEnumerable< T>
而不仅仅是IEnumerable
。Firstly, as others have said you can introduce your own methods without implementing interfaces anyway - you can write your own
Dispose
method without implementingIDisposable
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 withoutIEnumerable
being involved. The compiler effectively does compile-time duck typing on the namesGetEnumerator()
,Current
andMoveNext()
. 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 justIEnumerable
.是的,你可以。甚至你可以在
foreach
中使用它。唯一的问题是此类的对象无法转换为 IEnumerable,尽管它们实现了所需的方法。yes you can. even you can use it in
foreach
. The only problem that objects of this class can't be cast toIEnumerable
although they implement needed method.您没有理由必须实现
IEnumerable
才能创建一个名为GetEnumerator
并返回IEnumerator
的函数,这只意味着您不会'无法为需要 IEnumerable 的对象提供该类型的实例。There's no reason that you have to implement
IEnumerable
in order to create a function calledGetEnumerator
that returns anIEnumerator
, that just means that you won't be able to supply an instance of that type to something that expects anIEnumerable
.接口确保契约,这并不意味着您不能在未实现该接口的类上拥有与接口中的签名相同的方法。
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.