无效方差:类型参数必须始终有效但协变

Invalid variance: The type parameter must be invariantly valid but is covariant

这有什么问题吗?

// does not compile
interface IRepository<out T>
{
    Task<T> Get(int id);
}

编译器抱怨:

Invalid variance: The type parameter 'T' must be invariantly valid on ... 'T' is covariant.

但是,当我删除任务时,代码编译:

// compiles
interface IRepository<out T>
{
    T Get(int id);
}

为什么使接口异步会导致它无法编译?

正如 Asad 上面提到的,Task<T> 不能是协变的,因为它是 classMSDN 状态:

Only interface types and delegate types can have variant type parameters.

如果有协变 ITask<T> 接口 就好了。

谷歌搜索后,我在 visualstudio.uservoice.com. In the comments, Jeffrey Morse links to his implementation of ITask<T> 找到了这个建议。

杰夫干得好!