C++/CLI Generic::字典声明语法
我对 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 ^ ?
谢谢。
I'm been curious about the declaration syntax of Collections::Generic::Dictionary
class in C++/CLI.
Normally we declare a reference in a class and initialize it:
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>())
{...}
};
Could someone explains please why should the '^' absent there?
What's more, if I were to use the dictionary above as a TValue of another dictionary,
I have to declare it like this:
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 ^ ?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是
Dictionary
特有的。此语法是一种帮助将 C++ 语义映射到托管类型的方法。一般来说:大致相当于
C# 中的 if
ReferenceType
实现IDisposable
。完全可以这样写:This does not have theimplicit
IDisposable
support.另一个区别是您可以从方法返回ReferenceType^
,仅普通ReferenceType
不支持此功能。例如:将编译,
将自动(堆栈变量)脱糖提供类似的区别
编译器
,这些功能将熟悉的 RAII 习惯用法引入具有托管类型的 C++/CLI。
编辑:
是的,IDisposable 的 Dispose 方法类似于 C++ 析构函数。如果
ReferenceType
未实现IDisposable
(没有 dtor),并且它是唯一的成员,则A
也不会实现 < code>IDisposable (没有隐式 dtor)。在 C++/CLI 中,您可以通过提供 dtor(对于托管类型)来实现 IDisposable。This is not specific to
Dictionary
. This syntax is a way to help map C++ semantics onto managed types. In general:is roughly equivalent to
in C# if
ReferenceType
implementsIDisposable
. It is perfectly possible to writeThis does not have the implicit
IDisposable
support. The other difference is that you can return aReferenceType^
from a method, this is not supported with just plainReferenceType
. For example:will compile,
A similar distinction is provided for automatic (stack variables)
is desugared by the compiler to
These features bring the familiar idiom of RAII to C++/CLI with managed types.
EDIT:
Yes, the Dispose method of IDisposable is analogous to a C++ destructor. If
ReferenceType
doesn't implementIDisposable
(doesn't have a dtor), and it is the only member,A
will also not implementIDisposable
(not have an implicit dtor). In C++/CLI you implementIDisposable
by providing a dtor (for managed types).