C#Lambda令人费解的行为

时间:2009-10-29 16:50:38

标签: c# clr lambda

Func<Classification, string> test1 = c => c.Id = "x"; 
Func<Classification, string> test2 = c => { return c.Id = "x";}; 

我已经和lambda一起工作了将近一年左右,并且相当合理,但是今天我看着NBuilder并看到一个奇怪的Func似乎与这些例子不符。无论如何我都玩了它但是我不知道为什么上面的编译更不用说了。我们正在做一个作业,因此表达式不评估任何东西,对吧??? <或者

所以我想也许我错过了与lambda相关的东西,所以我尝试了别的东西:

    [Test]
    public void AmIGoingMad()
    {
        Assert.That(Test(),Is.Null); // not sure what to expect - compile fail?
    }

    public string Test()
    {
        string subject = "";
        return subject = "Matt";
    }

果然AmIGoingMad失败,实际上会返回“马特”。

为什么我们有这种行为?这记录在哪里?它纯粹是一种句法快捷方式吗?

我觉得我在理解lambda甚至是C#时错过了一些基本的东西。

感到愚蠢。

5 个答案:

答案 0 :(得分:9)

赋值语句具有返回值 - 该值是已分配的值。即使C有这个,所以你可以把如下的作业链接在一起:

a = b = c = d = 10;

对d的赋值的返回值为10,它被赋值给c,依此类推。

答案 1 :(得分:1)

你所看到的是分配链,这可以追溯到C / C ++。它可以支持这种情况:

int a = b = c = 0;

或者在某处我实际使用它:

public static IEnumerable<string> ReadLines(string filePath)
{
    using (var rdr = new StreamReader(filePath))
    {
       string line;
       while ( (line = rdr.ReadLine()) != null)  // <-----
       {
          yield return line;
       }
    }
}

答案 2 :(得分:1)

它有效,因为赋值c.Id = "x"的计算结果为“x”的值。例如,如果你想在一个语句中分配和检查一个值(有些人认为是不好的做法),你可以使用它,如下所示:

string s;
if((s = SomeFunction()) != null) { \\do something with s }

答案 3 :(得分:1)

正如其他人所说,赋值本身会返回一个值。

您也可以像这样利用它:

private List<string> theList;
public List<string> LazyList
{
  get { return theList ?? (theList = new List<string>()); }
}

答案 4 :(得分:0)

我不明白你的问题。

您发布的代码似乎误解了===之间的差异,然后明确表示您希望它使用=作为赋值运算符。< / p>

让我问你一个问题:

为什么你想要或期望这不能编译?

Assert.That(Test(),Is.Null); // not sure what to expect - compile fail?

基本上,你这样做:

String temp = Test();
Assert.That(temp, Is.Null);
相关问题