【问题标题】:Lambda expression with a void input带有 void 输入的 Lambda 表达式
【发布时间】:2013-05-29 00:06:59
【问题描述】:

好的,非常愚蠢的问题。

x => x * 2

是一个 lambda,表示与

的委托相同的事物
int Foo(x) { return x * 2; }

但是什么是 lambda 等价物

int Bar() { return 2; }

??

非常感谢!

【问题讨论】:

    标签: c# c#-3.0 lambda


    【解决方案1】:

    空值 lambda 等效项是 () => 2

    【讨论】:

    • 该死的,这太快了 :) 谢谢大家!
    【解决方案2】:

    那就是:

    () => 2
    

    示例用法:

    var list = new List<int>(Enumerable.Range(0, 10));
    Func<int> x = () => 2;
    list.ForEach(i => Console.WriteLine(x() * i));
    

    根据 cmets 的要求,以下是上述示例的细分...

    // initialize a list of integers. Enumerable.Range returns 0-9,
    // which is passed to the overloaded List constructor that accepts
    // an IEnumerable<T>
    var list = new List<int>(Enumerable.Range(0, 10));
    
    // initialize an expression lambda that returns 2
    Func<int> x = () => 2;
    
    // using the List.ForEach method, iterate over the integers to write something
    // to the console.
    // Execute the expression lambda by calling x() (which returns 2)
    // and multiply the result by the current integer
    list.ForEach(i => Console.WriteLine(x() * i));
    
    // Result: 0,2,4,6,8,10,12,14,16,18
    

    【讨论】:

    • 嗨,这似乎是一个很好的例子;你能用简单的英语逐句逐句解释吗? :)
    • @PussInBoots 添加了一些 cmets。希望有帮助!
    • 谢谢。仍然对 Func x 和 x() 感到有些困惑。我想我需要阅读更多关于 Func、delegate 和 lambdas 的内容。
    • 有人可以向我解释一下,与仅使用常量相比,这有什么优势?
    【解决方案3】:

    如果你没有参数,你可以使用 ()。

    () => 2;
    

    【讨论】:

      【解决方案4】:

      lmabda 是:

      () => 2
      

      【讨论】:

        猜你喜欢
        • 2013-07-02
        • 1970-01-01
        • 2021-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多