当我们在C# 4.0中定义接口时,可以将每个泛型参数标记为
问题:
如果编译器有推断出使用协变(
示例:
我是否混淆了事情?
谢谢
in
或out
。如果我们尝试将泛型参数设置为out并且会导致问题,则编译器会引发错误,不允许我们这样做。问题:
如果编译器有推断出使用协变(
out
)和逆变(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
我是否混淆了事情?
谢谢