2016-09-16 56 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