我有以下的接口和类:
private interface ITest<in T1, out T2>
{
}
private class TestClass
{
}
private class TestClass<T1, T2> : TestClass, ITest<T1, T2>
{
}
有了这些,我可以做到:
TestClass testBase = new TestClass<Parent, Child> ();
TestClass<Parent, Child> testGeneric = (TestClass<Parent, Child>)testBase; // Works fine
ITest<Parent, Parent> testInterface = (ITest<Parent, Parent>)testGeneric; // Works fine
但是如果我试图将两者结合起来,我就做不到:
ITest<Parent, Parent> testInterface = (ITest<Parent, Parent>)testBase; // Fail!
为什么我不能直接在这里进行强制类型转换?这只是C#类型转换或变体接口的限制吗?
如果接口的类型参数与泛型类的类型完全匹配,它实际上是可以工作的:
ITest<Parent, Child> testInterfaceExact = (ITest<Parent, Child>)testBase; // Works
Child
是否真的是Parent
的子类型? - Lee