这失败了
string temp = () => {return "test";};
与错误
无法将lambda表达式转换为“字符串”类型,因为它不是委托类型
错误是什么意思,我该如何解决?
Answers:
这里的问题是您已经定义了一个匿名方法,该方法返回a,string
但尝试将其直接分配给a string
。这是一个表达式,在调用时会产生一个表达式,而string
不是直接产生string
。需要将其分配给兼容的委托类型。在这种情况下,最简单的选择是Func<string>
Func<string> temp = () => {return "test";};
可以通过一点强制转换或使用委托构造函数来建立lambda的类型并随后进行调用来完成此操作。
string temp = ((Func<string>)(() => { return "test"; }))();
string temp = new Func<string>(() => { return "test"; })();
注意:两个样本都可以缩写为缺少 { return ... }
Func<string> temp = () => "test";
string temp = ((Func<string>)(() => "test"))();
string temp = new Func<string>(() => "test")();
Func<string> temp = () => "test";
。
string temp = new Func<string>(() => "test")();
您试图将函数委托分配给字符串类型。试试这个:
Func<string> temp = () => {return "test";};
您现在可以这样执行函数:
string s = temp();
现在,“ s”变量的值将为“ test”。
使用一些辅助函数和泛型,可以让编译器推断类型,并将其缩短一点:
public static TOut FuncInvoke<TOut>(Func<TOut> func)
{
return func();
}
var temp = FuncInvoke(()=>"test");
旁注:这也很好,因为您随后可以返回匿名类型:
var temp = FuncInvoke(()=>new {foo=1,bar=2});
您可以使用带有参数的匿名方法:
int arg = 5;
string temp = ((Func<int, string>)((a) => { return a == 5 ? "correct" : "not correct"; }))(arg);
匿名方法可以使用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();
}
}
}
这是使用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();
}
}
}