Cannot convert type 'Task' to 'Task'

后端 未结 3 1377
忘掉有多难
忘掉有多难 2020-12-03 10:49

I have the following function with a delegate parameter that accepts a type of one interface and returns a task of another.

public void Bar(Func

        
3条回答
  •  爱一瞬间的悲伤
    2020-12-03 11:38

    It seems like there's got to be a cleaner way of doing this, but it is possible to create a wrapping task of the correct type. I introduced a new function called GeneralizeTask().

    Task GeneralizeTask(Task task) 
        where TDerived : TBase 
    {
        var newTask = new Task(() => {
            if (task.Status == TaskStatus.Created) task.Start();
            task.Wait();
            return (TBase)task.Result;
        });
        return newTask;
    }
    

    Edit:

    As @EricLippert points out, this can be simplified significantly. I first tried to find such a way to implement this method, but couldn't find one that compiled. As it turned out, the real solution was even simpler than I imagined.

    async Task GeneralizeTask(Task task) 
        where TDerived : TBase 
    {
        return (TBase) await task;
    }
    

    You can then invoke Bar() like this.

    Bar(m => GeneralizeTask(DoSomething((Message)m)));
    

提交回复
热议问题