Downcasting interface references
I'm getting a run-time exception when I try to cast an object to an interface that I'm pretty sure it implements.
I have the following interfaces:
public interface class ISMILTimeContainer;
public interface class ISMILSequence : ISMILTimeContainer;
public interface class ISMILParallel : ISMILTimeContainer;
I have the following classes:
ref class TimeContainer : public ISMILTimeContainer;
ref class Sequence : public TimeContainer, ISMILSequence;
ref class Parallel : public TimeContainer, ISMILParallel;
Then, I try the following:
ISMILTimeContainer^ container = getSequence(); // returns a Sequence^
ISMILSequence^ sequence = static_cast<ISMILSequence^>(container);
This throws an exception at run-time:
Platform::InvalidCastException ^ at memory location 0x04AFD83C. HRESULT:0x80004002 No such interface supported
As far as I can tell, this should be working. Is there something wrong with what I'm trying to do, or do the symptoms indicate an implementation issue (something is different than what is claimed above)?
Your container
is an ISMILTimeContainer
created by implicit cast. This is upcasting, casting a derived class object (the return value of getSequence()
, a Sequence
) to a parent or base class object (the ISMILTimeContainer
).
When you then try to downcast to an ISMILSequence
in your next statement, because you have an inheritance chain, you pass compiler checks using static_cast<ISMILSequence^>
.
However, C++/CX also runs runtime checks [1], and in this case it seems that your container
variable, of type ISMILTimeContainer
, does not have all of the information required to form an ISMILSequence
in your second statement. Although an ISMILSequence
IS-A ISMILTimeContainer
, the opposite is not true.
For information about up-casting and down-casting, see [2] or other google results. The later sections in this blog post might be of help.
链接地址: http://www.djcxy.com/p/23288.html下一篇: 向下转换接口参考