【问题标题】:Is there any extension method which get void returning lambda expression ?是否有任何扩展方法可以使返回 lambda 表达式无效?
【发布时间】:2010-06-13 21:12:28
【问题描述】:

例如

int[] Array = { 1, 23, 4, 5, 3, 3, 232, 32, };

Array.JustDo(x => Console.WriteLine(x));

【问题讨论】:

  • 我知道我可以编写自己的扩展方法,但我想知道是否已经存在。

标签: c# .net linq extension-methods


【解决方案1】:

我认为您正在寻找Array.ForEach,它不需要您先转换为列表。

int[] a = { 1, 23, 4, 5, 3, 3, 232, 32, };
Array.ForEach(a, x => Console.WriteLine(x));

【讨论】:

  • int[] 数组没有那个扩展方法。
  • @Freshblood - 但数组类可以。您只需要像示例所示那样进行操作即可。
  • @Freshblood:如果您查看我的代码示例,Array 不是 int 数组的名称,而是 Array 类的名称。是的,正如我的代码演示的那样,它适用于 int 数组。你可以编译一下试试看。
  • @Brian 抱歉。乍一看我没有看到你定义了 int[] a 但我已经定义了 int[] 数组:) 这就是为什么我没有考虑你的扩展方法
  • @Freshblood:np,因此我不得不更改变量的名称:)
【解决方案2】:

您可以使用 Array.ForEach 方法

int[] array = { 1, 2, 3, 4, 5};
Array.ForEach(array, x => Console.WriteLine(x));

或制作自己的扩展方法

void Main()
{
    int[] array = { 1, 2, 3, 4, 5};
    array.JustDo(x => Console.WriteLine(x));
}

public static class MyExtension
{
    public static void JustDo<T>(this IEnumerable<T> ext, Action<T> a)
    {
        foreach(T item in ext)
        {
            a(item);
        }
    }
}

【讨论】:

  • int[] 数组没有那个扩展方法,但是很高兴知道集合有这个扩展。
  • 写扩展方法也不错。
【解决方案3】:

正如其他人所说,您可以使用Array.ForEach。不过,您可能想阅读Eric Lippert's thoughts on this

如果您在阅读后仍然想要它,System.Interactive 程序集中的Do 方法,它是Reactive Extensions 的一部分,作为EnumerableEx 的一部分。你可以这样使用它:

int[] array = { 1, 23, 4, 5, 3, 3, 232, 32, };   
array.Do(x => Console.WriteLine(x));

(我已经更改了变量的名称以避免混淆。通常最好不要将变量命名为与类型相同的名称。)

在 Reactive Extensions 中有很多很棒的东西值得一看...

【讨论】:

  • @Freshblood:不,它在 System.Interactive 程序集中,它是 Reactive Extensions 的一部分。我认为它仍然在 System.Linq 命名空间中。我将编辑我的帖子以使其更清晰。
猜你喜欢
  • 2012-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-20
  • 1970-01-01
  • 1970-01-01
  • 2017-04-19
相关资源
最近更新 更多