定义一个lambda函数并立即执行 [英] Define a lambda function and execute it immediately

查看:156
本文介绍了定义一个lambda函数并立即执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在定义一个lambda并通过立即附加()"来调用它.

I'm defining a lambda and calling it, by appending "()", immediately.

尝试:

int i = (() => 0) ();

错误:

错误CS0119:表达式表示预期为anonymous method', where a方法组'

那是为什么?

推荐答案

lambda只是不支持被执行.委托支持被执行. Lambda表达式可以隐式转换为委托类型.如果不要求这种转换,则不存在默认"委托类型.从.NET 2开始,我们通常将ActionFunc用于所有内容,但我们可以使用不同的委托类型.

A lambda just does not support being executed. A delegate supports being executed. A lambda expression can be implicitly converted to a delegate type. In case no such conversion is requested there is no "default" delegate type. Since .NET 2 we normally use Action and Func for everything but we could use different delegate types.

首先转换为委托,然后执行:

First convert to a delegate, then execute:

((Func<int>)(() => 0))()

有人可能会争辩说,如果没有其他要求,C#应该默认使用ActionFunc.从C#5开始,该语言没有这样做.

One could argue that C# should default to using Action and Func if nothing else was requested. The language does not do that as of C# 5.

这篇关于定义一个lambda函数并立即执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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