2010-12-06 54 views
0

我很好奇C++/CLI中Collections :: Generic :: Dictionary 類的聲明語法。C++/CLI通用::字典聲明語法

通常我們在一個類中聲明的引用,並初始化:

public ref class CDemo { 
    private: ClassA^m_InstanceA; 

    // Why the absence of '^'. 
    private: Dictionary<int, int> m_Dic; 

    CDemo() : 
     m_InstanceA(gcnew ClassA()), 
     m_Dic(gcnew Dictionary<int, int>()) 
    {...} 
}; 

可能有人請解釋爲什麼要「^」缺席呢?

更重要的是,如果我使用的TValue另一個字典, 上面的字典我要聲明的是這樣的:

Dictionary<T, Dictionary<T, T>^ > m_Dic; // A '^' in the TValue parameter, which is   
              // normal, but same question as above, 
              // I don't have to declare m_Dic as^? 

感謝。

+0

這是一個錯誤。查看構造函數生成的IL,注意如何創建兩個字典。 – 2010-12-06 17:23:37

回答

3

這不是特定於Dictionary。該語法是幫助將C++語義映射到託管類型的一種方法。一般來說:

ref class A 
{ 
    ReferenceType m_obj; 
}; 

大致相當於

class A : IDisposable 
{ 
    private ReferenceType m_obj; 
    void Dispose() { m_obj.Dispose(); } 
} 

在C#如果ReferenceType器具IDisposable。這是完全可能的寫

ref class A 
{ 
    ReferenceType^ m_obj; 
}; 

這沒有隱含的IDisposable支持。另一個區別是你可以從方法中返回一個ReferenceType^,這只是普通的ReferenceType不支持的。例如:

ref class A 
{ 
    ReferenceType^ m_obj; 
    ReferenceType^ GetIt() { return m_obj; } 
}; 

將編譯,

ref class A 
{ 
    ReferenceType m_obj; 
    ReferenceType GetIt() { return m_obj; } // won't compile 
    ReferenceType^ OtherGetIt() { return m_obj; } // neither will this 
}; 

類似的區別提供了一種用於自動(堆棧變量)

 ReferenceType local; 
     local.Stuff(); 

是由編譯器脫糖到

 try { 
     ReferenceType^ local = gcnew ReferenceType(); 
     local->Stuff(); 
     } finally { 
     delete local; // invokes Dispose() (~ReferenceType) 
     } 

這些功能將熟悉的RAII習慣用於託管類型的C++/CLI。

編輯:

是,IDisposable接口的Dispose方法類似於C++的析構函數。如果ReferenceType沒有實現IDisposable(沒有dtor),並且它是唯一的成員,A也不會實現IDisposable(沒有隱式的dtor)。在C++/CLI中,通過提供一個dtor(用於託管類型)來實現IDisposable

+0

感謝您的回答。你能再解釋第二點嗎? 「在C#中,如果ReferenceType實現IDisposable。這是完全可能的寫...」 IDisposable這裏是相同的C++/CLI的dtor? 如果C#類型沒有實現IDisposable接口,該怎麼辦? – Wilson 2010-12-06 05:31:57