在 .NET 3.5 List<> 中获得了一个 ForEach 方法。我注意到这在 IList<> 或 IEnumerable<> 上不存在,这里的想法是什么?还有另一种方法可以做到这一点吗?这样做的好方法和简单的方法?
我问是因为我在演讲中说总是使用更通用的界面。但是,如果我希望能够转身使用 ForEach,为什么还要使用 IList<> 作为返回类型呢?然后我最终会将它转换回列表<>。
在 .NET 3.5 List<> 中获得了一个 ForEach 方法。我注意到这在 IList<> 或 IEnumerable<> 上不存在,这里的想法是什么?还有另一种方法可以做到这一点吗?这样做的好方法和简单的方法?
我问是因为我在演讲中说总是使用更通用的界面。但是,如果我希望能够转身使用 ForEach,为什么还要使用 IList<> 作为返回类型呢?然后我最终会将它转换回列表<>。
这里的想法是什么?
您可以阅读Eric Lippert的博客了解未添加此功能的原因。
还有另一种方法可以做到这一点吗?这样做的好方法和简单的方法?
为什么不直接使用 foreach 关键字?我觉得它更具可读性。
foreach (var foo in ilist)
{
// etc...
}
如果您愿意,可以添加ForEach
扩展方法:IEnumerable<T>
public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
foreach (T item in enumeration)
{
action(item);
}
}
取自这里。
Why is ForEach
not in IEnumerable<T>
? Eric Lippert explains this nicely in his blog. Basically, LINQ is meant to be functional (no side effects), and ForEach
is decidedly non-functional.
But, why is it not in IList<T>
? Well... it should be!
它不在框架中(还),但Rx添加了 .Run(this IEnumerable enumerable) 扩展方法,该方法与 List 的自定义 ForEach 相同。在这成为标准框架的一部分之前,您必须自己编写或使用额外的依赖项。