Why is Task not co-variant?

前端 未结 2 1049
逝去的感伤
逝去的感伤 2020-11-28 11:50
class ResultBase {}
class Result : ResultBase {}

Task GetResult() {
    return Task.FromResult(new Result());
}

The compiler tel

2条回答
  •  迷失自我
    2020-11-28 12:28

    I realize I'm late to the party, but here's an extension method I've been using to account for this missing feature:

    /// 
    /// Casts the result type of the input task as if it were covariant
    /// 
    /// The original result type of the task
    /// The covariant type to return
    /// The target task to cast
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static async Task AsTask(this Task task) 
        where T : TResult 
        where TResult : class
    {
        return await task;
    }
    

    This way you can just do:

    class ResultBase {}
    class Result : ResultBase {}
    
    Task GetResultAsync() => ...; // Some async code that returns Result
    
    Task GetResultBaseAsync() 
    {
        return GetResultAsync().AsTask();
    }
    

提交回复
热议问题