.net - List.ForEach 方法和集合接口(interface)

标签 .net collections interface ienumerable ilist

在 .NET 3.5 中,List<> 获得了一个 ForEach 方法。我注意到这在 IList<> 或 IEnumerable<> 上不存在,这里的想法是什么?还有另一种方法吗?做到这一点的好而简单的捷径?

我问是因为我在演讲中演讲者说总是使用更通用的接口(interface)。 但是,如果我希望能够转身使用 ForEach,为什么还要使用 IList<> 作为返回类型?然后我最终会将其转换回 List<>。

最佳答案

what was the thinking here?

您可以阅读 Eric Lippertblog由于未添加此功能的原因。

Is there another way to do this? Nice and simple short way to do this?

为什么不直接使用 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);
    }
}

取自here .

关于.net - List.ForEach 方法和集合接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2961852/

相关文章:

c# - .Net如何检测在执行程序集时是否通过代码手动抛出内置异常

java - .Net 可以加载 IL 文件(例如 java 类文件),还是必须加载整个程序集?

java - 类型 T 不是通用的;它不能用参数 <?> 泛型函数中的错误进行参数化

java - 我怎样才能访问这个列表并且也是线程安全的?

collections - Kotlin:在 API 中公开不可变列表

java - 当多个重载合法时调用哪个方法?

excel - 在 VBA 中实现接口(interface)时,实现的功能需要是私有(private)的还是公有的?

c# - 类库的 app.config 中的绑定(bind)重定向有什么作用吗?

javascript - 对如何在来自 javascript 的 C# .NET 中实现 HMACSHA1 感到困惑

language-agnostic - "program to an interface"是什么意思?