【发布时间】:2016-12-09 11:59:03
【问题描述】:
我有以下接口和类:
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
【问题讨论】:
-
无法复制,在这里和on dotnetfiddle 工作正常。请提供minimal reproducible example 并提及您使用的编译器版本。
-
我希望这可以工作,
Child实际上是Parent的子类型吗?