0

当我编译代码时出现此错误,我无法弄清楚为什么 mcs 会查找错误的函数重载,我使用 mono 作为 git 的当前活动开发版本的最新版本,我检查了 TaskFactory 类源代码和函数存在!


TaskPoc.cs(30,20): 错误 CS1502: ' ' 的最佳重载方法匹配System.Threading.Tasks.TaskFactory.StartNew<bool>(System.Func<bool>, System.Threading.Tasks.TaskCreationOptions)有一些无效参数 /usr/local/lib/mono/4.5/mscorlib.dll (与先前错误相关的符号位置)TaskPoc。 cs(30,56):错误 CS1503:参数 `#1' 无法将 ` System.Func<TaskPoc.State,bool>' 表达式转换为类型 ` System.Func<bool>'


using System;
using System.Threading;
using System.Threading.Tasks;
namespace TaskPoc
{
  public class State
  {
    public int num;
    public string str;
  }

  public class App
  {
    public static void Main(string[] args)
    {
      State state = new State();
      state.num = 5;
      state.str = "Helllllllllllo";

      TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>(state);
      Task<bool> taskObj = taskCompletionSource.Task;

      Func<State, bool> userMethod = (stateObj) =>
        {
            bool result = TestMethod(stateObj.num, stateObj.str);
            taskCompletionSource.SetResult(result);
            return result;
        };

      Task.Factory.StartNew<bool>(userMethod, state);

      bool result2 = taskObj.Result;
      Console.WriteLine("Result: ", result2.ToString());
    }

    public static bool TestMethod(int num, string str)
    {
      Thread.Sleep(1000);
      Console.WriteLine(string.Format("{0} {1}", num, str));
      return true;
    }
  }
}
4

1 回答 1

3

我假设你想要这个重载:TaskFactory.StartNew<TResult>(Func<Object, TResult>, Object)

如您所见,Func<Object, TResult>must 的论点是Object,不是State

您可以按如下方式修复代码:

Func<object, bool> userMethod = (state) =>
{
    State stateObj = (State)state;
    bool result = TestMethod(stateObj.num, stateObj.str);
    taskCompletionSource.SetResult(result);
    return result;
};

请注意,您的代码可以缩短如下:

public static void Main(string[] args)
{
    int num = 5;
    string str = "Helllllllllllo";

    Task<bool> taskObj = Task.Run<bool>(() => TestMethod(num, str));

    bool result2 = taskObj.Result;
    Console.WriteLine("Result: {0}", result2);
}
于 2013-07-17T00:01:26.283 回答