shenjinwa 2021-05-15 22:30 采纳率: 33.3%
浏览 127
已采纳

C#中,Task(Action<object> action, object state)遇见的问题

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Threading;

namespace ConsoleApp中task的状态
{
    class Program
    {
        private static void Method(int i)
        {
            i =i *1000;
            Thread.Sleep(i);
        }
        static void Main(string[] args)
        {
            Action<int> action = new Action<int>(Method);

            Task task1 = new Task(action,null);
            task1.Start();


        }
    }
}

 代码这一部分,Task task1 = new Task(action,null);

提示报错原因是: 参数 1: 无法从“System.Action<int>”转换为“System.Action”   

 

  • 写回答

2条回答 默认 最新

  • 斯洛文尼亚旅游 2021-05-15 22:46
    关注

    task的重载没有int这种泛型,只有Action<object>,你传递Action<int>当然没法转换成action,改成下面就行了

    
            private static void Method(object state)
            {
                var o = (Data)state;
                int a = o.x;
                int b = o.y;
                int i = a * b;
                Console.WriteLine($"{a}和{b}相乘的结果是{i}");
            }
            static void Main(string[] args)
            {
                Action<object> action = new Action<object>(Method);
                Task task1 = new Task(action, new Data { x=1,y=2});
                task1.Start();
    
                Console.ReadKey();
            }
            public class Data { public int x { get; set; }public int y { get; set; } }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?