2016-09-16 57 views
0

我有一个返回一个接口引用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)). 

什么我们在这里失踪了吗?

+2

那么你缺少的代码将编译,初学者。 –

+2

没有迹象表明两个干涉是相关的。阅读[mcve]指导并[相应地发布]。 –

回答

0

我猜下面一行:

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