gpt4 book ai didi

c# - 无效方差 : The type parameter must be invariantly valid but is covariant

转载 作者:太空狗 更新时间:2023-10-30 01:02:40 25 4
gpt4 key购买 nike

这是怎么回事?

// 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);
}

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

最佳答案

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

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

要是有一个协变就好了 ITask<T> 界面

谷歌搜索后,我在 visualstudio.uservoice.com 找到了这个建议.在评论中,Jeffrey Morse 链接到他的 implementation of ITask<T> .

干得好,杰夫!

关于c# - 无效方差 : The type parameter must be invariantly valid but is covariant,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32877447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com