【问题标题】:Cast to child interface投射到子界面
【发布时间】:2016-09-16 15:12:45
【问题描述】:

我有一个返回接口引用IInterfaceA 的方法,并希望将其转换为IInterfaceB,这样做:

IInterfaceA a = SomeMethodThatReturnAnIInterfaceA();
IInterfaceB b = (IInterfaceB)a;

public IInterfaceA : OtherInterfaceA, OtherInterfaceB {}
public IInterfaceB : IInterfaceB {}

但在运行时我得到了:

Unable to cast COM object of type 'OPCAutomation.OPCGroupClass' to interface
type 'SemaforosNNM.OPC.OPCDaGroup'. This operation failed because the
QueryInterface call on the COM component for the interface with IID 
'{70F93164-7F80-37E3-8EFB-DAB08298316E}' failed due to the following error: 
Interfaz no compatible (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

我们在这里缺少什么?

【问题讨论】:

  • 好吧,对于初学者来说,您缺少可以编译的代码。
  • 没有迹象表明两个干扰是相关的。请阅读minimal reproducible example 指导和edit 相应帖子。

标签: c# oop interface


【解决方案1】:

我猜下面一行:

public interface IInterfaceB: IInterfaceB

在现实中:

public interface IInterfaceB : IInterfaceA

让我们输入更容易理解的名称:

public interface IAnimal //IInterfaceA
public interface ICat : IAnimal //IInterfaceB
public interface IDog : IAnimal //another IInterfaceB

IAnimal someAnimal = GetMeADog();
ICat catAndDogsDontMix = (ICat)someAnimal; //ouch!

您现在明白为什么不能转换为“子”接口了吗?

但奇怪的是您显示的是运行时错误;您发布的代码甚至不应该编译。您确定您的代码正确地重现了您的问题吗?也许a 被输入object

【讨论】: