【问题标题】:What is the requirement for a collection in order that we can put a foreach on it?集合的要求是什么,以便我们可以在其上放置一个 foreach?
【发布时间】:2023-03-09 15:04:01
【问题描述】:
为了让我们可以在 c# 中将 foreach 放在集合上,对集合有什么要求?我们可以为每种类型添加哪些类型?
编辑 1:任何人都可以想出实现 Foreach 的用户定义集合的示例代码。
【问题讨论】:
-
阅读此blogs.msdn.com/b/ericlippert/archive/2011/06/30/…。 What is required is that the type of the collection must have a public method called GetEnumerator, and that must return some type that has a public property getter called Current and a public method MoveNext that returns a bool.
标签:
c#
collections
foreach
【解决方案2】:
普遍接受的是您需要实现IEnumerable 或IEnumerable<T>,但您可以从Eric 的帖子Following the pattern 中读到事实并非如此
要求是集合的类型必须有一个公共的
称为 GetEnumerator 的方法,它必须返回一些具有
公共属性 getter 称为 Current 和公共方法 MoveNext
返回一个布尔值。
【解决方案3】:
唯一的正式要求是它有一个名为GetEnumerator() 的方法,它返回something,它有一个SomeType Current {get;} 属性和一个bool MoveNext() 方法。然而,最常见的是,这是通过实现IEnumerable/IEnumerable<T> 接口来完成的。实际上,预计您将实现此接口(旧方法实际上是作为预泛型优化),并且使用该接口将允许消费者将您的集合与 LINQ 和集合之类的东西一起使用-初始化器。
在有趣的情况下,最简单的实现方式是通过“迭代器块”。例如:
class Foo : IEnumerable<int> {
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
public IEnumerator<int> GetEnumerator() {
yield return 16;
yield return 12;
yield return 31;
// ^^ now imagine the above was a loop over some internal structure -
// for example an array, list, linked-list, etc, with a "yield return"
// per item
}
}