2010-12-06 56 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