在C ++/CLI中创建时初始化静态字典 [英] Initialize static Dictionary while creating in C++/CLI

查看:128
本文介绍了在C ++/CLI中创建时初始化静态字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我看到了创建静态字典并对其进行初始化的C#代码:

Today I saw C# code that creates static dictionary and initializes it:

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

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

but when I decided to write same code for C++/CLI, an error occurred. Here is my attempt:

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"},
    };

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

Can I do this and if so, how?

推荐答案

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

C# 3.0 and later allows users to define an "initializer"; for collections, that's a series of elements, which for Dictionaries is streamlined to keys and values. C++.NET to my knowledge does not have this language feature. See this question: it's very similar: Array initialization in Managed C++. Array initializers are the ONLY such initializer in C++; other collections do not offer them in C++.

基本上,您的主要选择是声明一个静态构造函数,然后在其中初始化字典.

Basically, your main option is to declare a static constructor and initialize your dictionary in there.

这篇关于在C ++/CLI中创建时初始化静态字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆