What is wrong with this?
// does not compile
interface IRepository<out T>
{
Task<T> Get(int id);
}
The compiler complains:
Invalid variance: The type parameter 'T' must be invariantly valid on ... 'T' is covariant.
However, when I remove the Task, the code compiles:
// compiles
interface IRepository<out T>
{
T Get(int id);
}
Why would making an interface asynchronous cause it to not compile?
As Asad mentioned above, Task<T>
cannot be covariant because it is a class . The MSDN states:
Only interface types and delegate types can have variant type parameters.
If only there was a covariant ITask<T>
interface .
After some googling, I found this suggested at visualstudio.uservoice.com . In the comments, Jeffrey Morse links to his implementation of ITask<T>
.
Nice work Jeff!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.