考虑ITest
使用协变类型参数的泛型接口、实现接口T
的泛型类、类和子类:Test
A
B
interface ITest<out T>
{
T prop{ get;}
}
class Test<T> : ITest<T>
{
public T prop{ get {
return default(T);
}}
}
class A {
}
class B: A {
}
以下代码编译没有错误,但会引发运行时异常System.ArrayTypeMismatchException
:
ITest<A>[] a = new ITest<A>[1];
a[0] = new Test<B>(); //<-- throws runtime exception
但这段代码工作得很好:
ITest<A> r = new Test<B>();
这已在Mono 2.10.2
( Unity3d 4.1
) 上进行了测试。我认为这在某种程度上与数组中的破坏协方差有关(参见http://blogs.msdn.com/b/ericlippert/archive/2007/10/17/covariance-and-contravariance-in-c-part-two-数组协方差.aspx)。
我不清楚为什么分配数组插槽时发生的类型检查没有考虑协方差。