96

这失败了

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

有错误

无法将 lambda 表达式转换为类型“字符串”,因为它不是委托类型

错误是什么意思,我该如何解决?

4

6 回答 6

142

这里的问题是您定义了一个匿名方法,该方法返回 astring但试图将其直接分配给 a string。它是一个表达式,在调用时会产生 astring它不是直接 a 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")();
于 2012-05-09T17:14:20.123 回答
18

您正在尝试将函数委托分配给字符串类型。试试这个:

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

您现在可以这样执行该函数:

string s = temp();

“s”变量现在将具有值“test”。

于 2012-05-09T17:15:45.200 回答
8

使用一点辅助函数和泛型,您可以让编译器推断类型,并缩短一点:

public static TOut FuncInvoke<TOut>(Func<TOut> func)
{
    return func();
}

var temp = FuncInvoke(()=>"test");

旁注:这也很好,因为您可以返回匿名类型:

var temp = FuncInvoke(()=>new {foo=1,bar=2});
于 2013-06-05T04:05:44.870 回答
6

您可以使用带有参数的匿名方法:

int arg = 5;

string temp = ((Func<int, string>)((a) => { return a == 5 ? "correct" : "not correct"; }))(arg);
于 2016-01-09T08:31:24.827 回答
3

匿名方法可以使用 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();
        }
    }
}
于 2017-12-12T06:41:55.287 回答
0

这是使用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();
        }
    }
}
于 2020-04-29T23:34:31.777 回答