What is the difference between new Action() and a lambda?

后端 未结 3 1882
逝去的感伤
逝去的感伤 2020-12-07 22:53

So when I write something like this

Action action = new Action(()=>_myMessage = \"hello\");

Refactor Pro! Highlights this as a redundant

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 23:26

    Have you verified the second line actually compiles? It should not compile because C# does not support assigning a lambda expression to an implicitly typed variable (CS0815). This line will work in VB.Net though because it supports anonymous delegate creation (starting in VB 9.0).

    The Rhino Mocks version does not compile for the same reason the second line should not compile. C# will not automatically infer a type for a lambda expression. Lambda expressions must be used in a context where it is possible to determine the delegate type they are intended to fulfill. The first line works great because the intended type is clear: Action. The Rhino Mocks version does not work because Delegate is more akin to an abstract delegate type. It must be a concrete delegate type such as Action or Func.

    For a detailed discussion on this topic, you should read Eric Lippert's blog entries on the subject: http://blogs.msdn.com/ericlippert/archive/2007/01/11/lambda-expressions-vs-anonymous-methods-part-two.aspx

提交回复
热议问题