2014-11-04 26 views
7

當我試圖將一個對象轉換爲我非常確定它實現的接口時,我得到了運行時異常。向下轉換接口參考

我有以下接口:

public interface class ISMILTimeContainer; 
public interface class ISMILSequence : ISMILTimeContainer; 
public interface class ISMILParallel : ISMILTimeContainer; 

我有以下類別:

ref class TimeContainer : public ISMILTimeContainer; 
ref class Sequence : public TimeContainer, ISMILSequence; 
ref class Parallel : public TimeContainer, ISMILParallel; 

然後,我嘗試以下方法:

ISMILTimeContainer^ container = getSequence(); // returns a Sequence^ 
ISMILSequence^ sequence = static_cast<ISMILSequence^>(container); 

這將引發異常在運行時間:

Platform :: InvalidCastException ^在內存位置0x04AFD83C。 HRESULT:0x80004002沒有這樣的接口支持

據我所知,這應該是工作。我正在嘗試做什麼,或者症狀表明是否存在執行問題(與上述要求不同)?

+1

你可以顯示'getSequence'嗎?我試圖複製你的代碼,並沒有得到一個例外。對我來說它有效。所有我改變的是調用'getSequence'這一行:'ISMILTimeContainer^container = ref new Sequence();'也許'getSequence'不返回'Sequence'? – 2014-11-08 02:17:42

+0

在WinRT中沒有繼承類的事情。它內部使用合成完成。我認爲在這種情況下,你可以使用safe_cast,它應該「跨越」而不是上下。把它想象成我猜想的尋路線。 – 2014-11-08 14:12:35

回答

3

您的container是由隱式轉換創建的ISMILTimeContainer。這是向上轉換,將派生類對象(返回值getSequence()Sequence)轉換爲父類或基類對象(ISMILTimeContainer)。

當您在下一條語句中嘗試向下傾倒到ISMILSequence時,由於您有繼承鏈,因此您使用static_cast<ISMILSequence^>通過編譯器檢查。

然而,C++/CX還運行運行時檢查[1],在這種情況下,似乎你container變量ISMILTimeContainer型的,不都在你的第二份聲明,以形成ISMILSequence所需的信息。儘管IS-A ISMILTimeContainer相反,但事實並非如此。

有關上鑄和下鑄的信息,請參閱[2]或其他谷歌搜索結果。本博客文章後面的部分可能會有所幫助。