为什么不能C#中使用内联匿名lambda表达式或代表? [英] Why can't c# use inline anonymous lambdas or delegates?

查看:344
本文介绍了为什么不能C#中使用内联匿名lambda表达式或代表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的措辞恰当,我的问题的称号。

I hope I worded the title of my question appropriately.

在C#中我可以使用lambda表达式(作为代表),或上了年纪的委托语法来做到这一点:

In c# I can use lambdas (as delegates), or the older delegate syntax to do this:

Func<string> fnHello = () => "hello";
Console.WriteLine(fnHello());

Func<string> fnHello2 = delegate()
{
    return "hello 2";
};
Console.WriteLine(fnHello2());

那么,为什么我不能内联拉姆达或委托身体,避免捕捉它在一个名为变量(使其匿名)?

So why can't I "inline" the lambda or the delegate body, and avoid capturing it in a named variable (making it anonymous)?

// Inline anonymous lambda not allowed
Console.WriteLine(
    (() => "hello inline lambda")()
);

// Inline anonymous delegate not allowed
Console.WriteLine(
    (delegate() { return "hello inline delegate"; })()
);

这在JavaScript(只是比较)工作的一个例子是:

An example that works in javascript (just for comparison) is:

alert(
    (function(){ return "hello inline anonymous function from javascript"; })()
);

这产生预期的警告框。

Which produces the expected alert box.

更新
看来你的可以的在C#中联匿名的lambda,如果将适当的,但()的开工量,使其不羁。

UPDATE: It seems you can have an inline anonymous lambda in C#, if you cast appropriately, but the amount of ()'s starts to make it unruly.

// Inline anonymous lambda with appropriate cast IS allowed
Console.WriteLine(
    ((Func<string>)(() => "hello inline anonymous lambda"))()
);

或许编译器不能推断匿名委托的SIG知道哪些Console.WriteLine()你想打电话?有谁知道为什么需要这个特定的投?

Perhaps the compiler can't infer the sig of the anonymous delegate to know which Console.WriteLine() you're trying to call? Does anyone know why this specific cast is required?

推荐答案

lambda表达式在C#中没有的类型,直到他们在他们强制转换为委托或防爆pression类型上下文中使用。这就是为什么你不能说

Lambdas in C# do not have types, until they are used in a context that casts them to a delegate or Expression type. That's why you can't say

var x = () => "some lambda";

您可能会喜欢

<一个href=\"http://blogs.msdn.com/ericlippert/archive/2007/01/11/lambda-ex$p$pssions-vs-anonymous-methods-part-two.aspx\">http://blogs.msdn.com/ericlippert/archive/2007/01/11/lambda-ex$p$pssions-vs-anonymous-methods-part-two.aspx

<一个href=\"http://blogs.msdn.com/ericlippert/archive/2007/01/12/lambda-ex$p$pssions-vs-anonymous-methods-part-three.aspx\">http://blogs.msdn.com/ericlippert/archive/2007/01/12/lambda-ex$p$pssions-vs-anonymous-methods-part-three.aspx

这篇关于为什么不能C#中使用内联匿名lambda表达式或代表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆