您的位置:首页 > 编程语言 > C#

C#匿名方法返回值赋值给变量

2016-05-03 16:49 651 查看
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"; })();

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")();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: