为什么 c# 不能使用内联匿名 lambda 或委托? [英] Why can't c# use inline anonymous lambdas or delegates?

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

问题描述

我希望我的问题标题措辞得当.

I hope I worded the title of my question appropriately.

在 c# 中,我可以使用 lambdas(作为委托)或旧的委托语法来执行此操作:

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());

那么为什么我不能内联" lambda 或委托主体,并避免在命名变量中捕获它(使其匿名)?

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"; })()
);

产生预期的警告框.

更新:如果您进行适当的转换,您似乎可以在 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?

推荐答案

C# 中的 Lambda 没有类型,除非在将它们转换为委托或表达式类型的上下文中使用它们.这就是为什么你不能说

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";

你可能会喜欢

http://blogs.msdn.com/ericlippert/archive/2007/01/11/lambda-expressions-vs-anonymous-methods-part-two.aspx

http://blogs.msdn.com/ericlippert/archive/2007/01/12/lambda-expressions-vs-anonymous-methods-part-three.aspx

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

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