为什么给出以下课程
class ParentClass<T>{ }
class ChildClass : IInterface{ }
interface IInterface{ }
我得到一个编译时错误“无法将类型”时,我尝试转换从类型ParentClass<ChildClass>
到ParentClass<IInterface>
,与下面的代码。
var concreteGeneric = new ParentClass<ChildClass>();
var interfaceGeneric = (ParentClass<IInterface>)concreteClass;
这里需要的是协方差,(如@xanatos所述)仅支持接口。如果将接口添加到ParentClass,则可以进行转换IParentClass<IInterface>
并获得所需的功能。
class ParentClass<T> : IParentClass<T> where T : IInterface { }
class ChildClass : IInterface { }
interface IInterface { }
interface IParentClass<out T> where T : IInterface { }
public void TestMethodX()
{
var concreteGeneric = new ParentClass<ChildClass>();
var interfaceGeneric = (IParentClass<IInterface>)concreteGeneric;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句