转换为子界面

时间:2016-09-16 15:12:45

标签: c# oop interface

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

我们在这里缺少什么?

1 个答案:

答案 0 :(得分: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