无法将实例类型转换为实例实现接口的接口类型

诺夫

为什么给出以下课程

class ParentClass<T>{   }
class ChildClass : IInterface{  }
interface IInterface{   }

我得到一个编译时错误“无法将类型”时,我尝试转换从类型ParentClass<ChildClass>ParentClass<IInterface>,与下面的代码。

var concreteGeneric = new ParentClass<ChildClass>();
var interfaceGeneric = (ParentClass<IInterface>)concreteClass;
Grax32

这里需要的是协方差,(如@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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

关闭无法隐式转换为通用接口类型的成员的通用接口的类的实例

将具体的实现类型转换为通用接口类型

Typescript将未知类型转换为接口类型

接口类型实例来自哪个类

无效的类型断言:无法将os.Stdout转换为接口类型io.ReadWriter?

foreach循环无法将类型转换为它实现的接口

无法将类型为“ System .__ ComObject”的COM对象转换为接口类型为“ EnvDTE.Project”

无法将类型为“ System .__ ComObject”的COM对象转换为接口类型为“ Microsoft.Office.Interop.Excel.Worksheets”

SAP:无法将“System.__ComObject”类型的 COM 对象转换为接口类型“sapfewse.GuiTextField”

Typescript接口类型值转换为联合类型

使用C#和反射将接口类型转换为具体类型

将继承类型的对象列表转换为新的接口类型列表

当泛型类型实现接口时,无法将Object的数组转换为泛型类型的数组

为什么我需要在C#显式实现中将'this'转换为接口类型?

当无法实例化接口时,如何将类实例强制转换为接口?

将使用URLClassLoader创建的对象转换为接口类型

在VBA中强制转换为接口类型

Swift:从接口类型数组转换为对象数组崩溃

无法将子类型列表传递到接口类型列表(由子类型实现)到 Visual Basic 中的函数 + 也不能强制转换

如何将二维地图从Firestore转换为Typescripts接口类型

HandlerFunc(f)如何将函数转换为接口类型?

将字节数组解组到接口,然后将该接口类型强制转换为struct不起作用?

T4MVC:System.InvalidCastException:无法将类型为System .__ ComObject的COM对象转换为接口类型为EnvDTE80.CodeClass2。

接口类型的变量

接口类型推断

接口类型返回

接口类型推断

无法将类型[具体]隐式转换为[接口]

将接口类型作为参数传递