转发界面参考

7 casting c++-cx

当我尝试将对象转换为我非常确定它实现的接口时,我遇到了运行时异常.

我有以下接口:

public interface class ISMILTimeContainer;
public interface class ISMILSequence : ISMILTimeContainer;
public interface class ISMILParallel : ISMILTimeContainer;
Run Code Online (Sandbox Code Playgroud)

我有以下课程:

ref class TimeContainer : public ISMILTimeContainer;
ref class Sequence : public TimeContainer, ISMILSequence;
ref class Parallel : public TimeContainer, ISMILParallel;
Run Code Online (Sandbox Code Playgroud)

然后,我尝试以下方法:

ISMILTimeContainer^ container = getSequence(); // returns a Sequence^
ISMILSequence^ sequence = static_cast<ISMILSequence^>(container);
Run Code Online (Sandbox Code Playgroud)

这会在运行时抛出异常:

Platform :: InvalidCastException ^在内存位置0x04AFD83C.HRESULT:0x80004002不支持此类接口

据我所知,这应该是有效的.我正在尝试做什么有问题,或症状是否表明实施问题(某些事情与上述要求不同)?

chr*_*244 3

containerISMILTimeContainer由隐式强制转换创建的。这是向上转换,将派生类对象( , getSequence()a的返回值Sequence)转换为父类或基类对象(ISMILTimeContainer

然后,当您尝试ISMILSequence在下一个语句中向下转换为 an 时,因为您有继承链,所以您可以使用以下命令通过编译器检查static_cast<ISMILSequence^>

然而,C++/CX 也运行运行时检查[1],在这种情况下,container类型为 的变量ISMILTimeContainer似乎没有ISMILSequence在第二个语句中形成 an 所需的所有信息。虽然是ISMILSequenceIS-AISMILTimeContainer,但反之则不然。

有关向上转换和向下转换的信息,请参阅[2]或其他 google 结果。本博文的后面部分可能会有所帮助。