C# 如何使用匿名方法返回值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10520892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return value with anonymous method?
提问by 4thSpace
This fails
这失败了
string temp = () => {return "test";};
with the error
有错误
Cannot convert lambda expression to type 'string' because it is not a delegate type
无法将 lambda 表达式转换为类型“字符串”,因为它不是委托类型
What does the error mean and how can I resolve it?
错误是什么意思,我该如何解决?
采纳答案by JaredPar
The problem here is that you've defined an anonymous method which returns a stringbut are trying to assign it directly to a string. It's an expression which when invoked produces a stringit's not directly a string. It needs to be assigned to a compatible delegate type. In this case the easiest choice is Func<string>
这里的问题是您定义了一个匿名方法,该方法返回 astring但试图将其直接分配给 a string。这是一个表达式,在调用时会生成 astring它不是直接的 a string。它需要分配给兼容的委托类型。在这种情况下,最简单的选择是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.
这可以在一行中通过一些强制转换或使用委托构造函数来建立 lambda 的类型,然后进行调用。
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 ... }
注意:两个样本都可以缩短为缺少 { return ... }
Func<string> temp = () => "test";
string temp = ((Func<string>)(() => "test"))();
string temp = new Func<string>(() => "test")();
回答by Dave Swersky
You are attempting to assign a function delegateto a string type. Try this:
您正在尝试将函数委托分配给字符串类型。尝试这个:
Func<string> temp = () => {return "test";};
You can now execute the function thusly:
您现在可以这样执行函数:
string s = temp();
The "s" variable will now have the value "test".
“s”变量现在将具有值“test”。
回答by joeriks
Using a little helper function and generics you can let the compiler infer the type, and shorten it a little bit:
使用一些辅助函数和泛型,您可以让编译器推断类型,并将其缩短一点:
public static TOut FuncInvoke<TOut>(Func<TOut> func)
{
return func();
}
var temp = FuncInvoke(()=>"test");
Side note: this is also nice as you then are able to return an anonymous type:
旁注:这也很好,因为您可以返回匿名类型:
var temp = FuncInvoke(()=>new {foo=1,bar=2});
回答by HamidReza
you can use anonymous method with argument :
您可以使用带参数的匿名方法:
int arg = 5;
string temp = ((Func<int, string>)((a) => { return a == 5 ? "correct" : "not correct"; }))(arg);
回答by Debendra Dash
An anonymous method can return a value using a func delegate. Here is an example where I have shown how to return a value using an anonymous method.
匿名方法可以使用 func 委托返回一个值。这是我展示如何使用匿名方法返回值的示例。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Func<int, int> del = delegate (int x)
{
return x * x;
};
int p= del(4);
Console.WriteLine(p);
Console.ReadLine();
}
}
}
回答by wbadry
This is another example using C# 8(could also work with other .NET versions supporting parallel tasks)
这是使用C# 8 的另一个示例(也可以与支持并行任务的其他 .NET 版本一起使用)
using System;
using System.Threading.Tasks;
namespace Exercise_1_Creating_and_Sharing_Tasks
{
internal static class Program
{
private static int TextLength(object o)
{
Console.WriteLine($"Task with id {Task.CurrentId} processing object {o}");
return o.ToString().Length;
}
private static void Main()
{
const string text1 = "Welcome";
const string text2 = "Hello";
var task1 = new Task<int>(() => TextLength(text1));
task1.Start();
var task2 = Task.Factory.StartNew(TextLength, text2);
Console.WriteLine($"Length of '{text1}' is {task1.Result}");
Console.WriteLine($"Length of '{text2}' is {task2.Result}");
Console.WriteLine("Main program done");
Console.ReadKey();
}
}
}

