【发布时间】:2010-04-28 21:55:05
【问题描述】:
当我们在 C# 4.0 中定义我们的接口时,我们可以将每个泛型参数标记为in 或out。如果我们尝试将泛型参数设置为 out 并且会导致问题,编译器会引发错误,不允许我们这样做。
问题:
如果编译器有办法推断covariance (out) 和contravariance(in) 的有效用途,为什么我们必须这样标记接口?让我们像往常一样定义接口还不够吗?当我们尝试在客户端代码中使用它们时,如果我们尝试以不安全的方式使用它们会引发错误?
示例:
interface MyInterface<out T> {
T abracadabra();
}
//works OK
interface MyInterface2<in T> {
T abracadabra();
}
//compiler raises an error.
//This makes me think that the compiler is cappable
//of understanding what situations might generate
//run-time problems and then prohibits them.
还有,
这不是Java在相同情况下所做的吗?据我记得,你只是做类似的事情
IMyInterface<? extends whatever> myInterface; //covariance
IMyInterface<? super whatever> myInterface2; //contravariance
还是我在混合?
谢谢
【问题讨论】:
标签: c# java generics covariance contravariance