如何使用匿名方法的返回值? [英] How to return value with anonymous method?

查看:152
本文介绍了如何使用匿名方法的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这失败

string temp = () => {return "test";};

与错误

无法将拉姆达EX pression键入'串',因为它不是一个委托类型

Cannot convert lambda expression to type 'string' because it is not a delegate type

什么是错误的意思是,我怎么能解决呢?

What does the error mean and how can I resolve it?

推荐答案

这里的问题是,你定义它返回一个字符串匿名方法,但正在努力直接分配到一个字符串。这是它被调用时产生字符串的前pression 它不是直接在字符串。它需要被分配给兼容的委托类型。在这种情况下,最简单的选择是 Func键<字符串>

The problem here is that you've defined an anonymous method which returns a string but are trying to assign it directly to a string. It's an expression which when invoked produces a string it's not directly a string. It needs to be assigned to a compatible delegate type. In this case the easiest choice is Func<string>

Func<string> temp = () => {return "test";};

这可以在一个线由一个位的铸造或使用委托构造建立拉姆达随后调用的类型来进行。

This can be done in one line by a bit of casting or using the delegate constructor to establish the type of the lambda followed by an invocation.

string temp = ((Func<string>)(() => { return "test"; }))();
string temp = new Func<string>(() => { return "test"; })();

请注意:这两个示例可以缩短到EX pression形式缺乏 {返回...}

Note: Both samples could be shorted to the expression form which lacks the { return ... }

Func<string> temp = () => "test";
string temp = ((Func<string>)(() => "test"))();
string temp = new Func<string>(() => "test")();

这篇关于如何使用匿名方法的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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