在C++/CLI中创建时初始化静态字典

Vik*_*yan 9 .net static dictionary c++-cli initialization

今天我看到C#代码创建静态字典并初始化它:

public static readonly Dictionary<string, string> dict = new Dictionary<string, string>()
        {
            {"br","value1"},
            {"cn","value2"},
            {"de","value3"},
        };
Run Code Online (Sandbox Code Playgroud)

但是当我决定为C++/CLI编写相同的代码时,发生了错误.这是我的尝试:

static System::Collections::Generic::Dictionary<System::String^, System::String^>^ dict = gcnew System::Collections::Generic::Dictionary<System::String^, System::String^>( )
    {
        {"br","value1"},
        {"cn","value2"},
        {"de","value3"},
    };
Run Code Online (Sandbox Code Playgroud)

我可以这样做,如果是这样,怎么样?

Kei*_*thS 8

C#3.0及更高版本允许用户定义"初始化程序"; 对于集合,这是一系列元素,用于字典简化为键和值.据我所知,C++.NET没有这种语言功能.看到这个问题:它非常相似:托管C++中的数组初始化.数组初始化器是C++中唯一的初始化器; 其他集合不提供C++版本.

基本上,你的主要选择是声明一个静态构造函数并在那里初始化你的字典.