【问题标题】:C# Functional Programming LambdaC# 函数式编程 Lambda
【发布时间】:2015-12-19 02:55:57
【问题描述】:

我不明白为什么下面的代码有输出 230。请帮忙。 代码和输出发布在下面。您可以使用 linqpad 编辑下面的代码,也可以阅读下面的代码。

void Main() {
    int ten = 10;
    int twenty = 20;
    int thirty = 30;

    int temp = 10.Where(t => 20); // X.Where(10,20);
    int result0 = temp.Select(t => 30);  
    result0.Dump("result0");

    int result1 = 
        from c in ten 
        where twenty 
        select thirty;    

    result1.Dump("result1");

    int result2 = 
        ten.Where(t => twenty).Select(t => thirty);

    result2.Dump("result2");
}

static class X {
    public static int Where(this int c, Func<int, int> f) {
        return c * f(0); 
    }
    public static int Select(this int c, Func<int, int> f) {
        return c + f(0); 
    }
}

输出:

result0
230 

result1
230 

result2
230

【问题讨论】:

  • 这段代码伤害了我的眼睛。你到底想达到什么目的?
  • 编译成哪种语言?
  • 提示:t =&gt; 20 是一个总是返回 20 的函数。它完全忽略了它的参数。
  • 我想你完全不知道你在那里做什么。
  • 无法编译,至少10.Where(t =&gt; 20);

标签: c# linq functional-programming


【解决方案1】:

静态方法Where返回c * f(0) 静态方法Select 返回c + f(0)

int temp = 10.Where(t =&gt; 20); 行将导致10 * 20 = 200
int result0 = temp.Select(t =&gt; 30); 行将导致 200 + 30 = 230

附加代码只是使用不同的语法执行相同的计算。
因此,结果是一个可预测的230

如果您想知道为什么 f(0) 中的零不会导致零。
不管t如何,lambda t =&gt; 20 返回 20
如果要返回值,需要改成t =&gt; t

在这种情况下,将返回零。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 2010-09-06
    • 1970-01-01
    • 2016-07-12
    • 2018-01-25
    • 2020-12-13
    相关资源
    最近更新 更多