2011-05-16 479 views
8

今天,當我看到創建的靜態辭典並對其進行初始化ç#代碼:初始化靜態字典在C++/CLI創造

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

,但是當我決定寫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"}, 
    }; 

我能做到這一點,如果是的話,怎麼樣?

+0

可能的[C++ CLI集合初始值設定語法]的副本(http://stackoverflow.com/questions/1923928/c-cli-collection-initializer-syntax) – 2011-05-16 18:13:58

回答

6

C#3.0及更高版本允許用戶定義「初始化程序」;對於集合而言,這是一系列元素,對於字典而言,這些元素簡化爲鍵和值。據我所知,C++。NET沒有這種語言功能。看到這個問題:它非常相似:Array initialization in Managed C++。數組初始化器是C++中唯一的這種初始化器;其他集合在C++中不提供它們。

基本上,你的主要選擇是聲明一個靜態構造函數並在那裏初始化你的字典。

3

這種類型的Dictionary<T>初始化不是類本身,而是C#編譯器的一個特性。它將其轉換爲用於創建Dictionary<T>對象的單獨聲明,以及每個鍵/值對的創建和添加。我不相信C++編譯器提供了相同的功能。

+0

這意味着我無法像初始化那樣初始化它C# ? – 2011-05-16 18:15:25

+1

對,它需要以不同的方式完成。 – dlev 2011-05-16 18:17:25

+0

基本上,是的。這是C#語言功能在託管C++中不可用。 – KeithS 2011-05-16 18:17:51

0

我的做法是(.NET 4.5):

// file.h 
using namespace System; 
using namespace System::Collections::Generic; 
// SomeClass 
public://or private: 
    static Dictionary<String^, String^>^ dict = dictInitializer(); 
private: 
    static Dictionary<String^, String^>^ dictInitializer(); 

// file.cpp 
#include "file.h" 
Dictionary<String^, String^>^ SomeClass::dictInitializer(){ 
    Dictionary<String^, String^>^ dict = gcnew Dictionary<String^, String^>; 
    dict->Add("br","value1"); 
    dict->Add("cn","value2"); 
    dict->Add("de","value3"); 
    return dict; 
} 
0

這是可能的! :-)
不是直接的,而是用一個小助手功能,您可以創建和初始化一個字典中的一行代碼:

// helper class 
generic <class TKey, class TValue> 
ref class CDict 
{ 
public: 
    static Dictionary<TKey, TValue>^ CreateDictionary (...array<KeyValuePair<TKey, TValue>>^ i_aValues) 
    { 
    Dictionary<TKey, TValue>^ dict = gcnew Dictionary<TKey, TValue>; 
    for (int ixCnt = 0; ixCnt < (i_aValues ? i_aValues->Length : 0); ixCnt++) 
     dict->Add (i_aValues[ixCnt].Key, i_aValues[ixCnt].Value); 
    return dict; 
    } 
}; 

// Test 
ref class CTest 
{ 
public: 
    static Dictionary<int, String^>^ ms_dict = CDict<int, String^>::CreateDictionary (gcnew array<KeyValuePair<int, String^>> 
    { 
    KeyValuePair<int, String^>(1, "A"), 
    KeyValuePair<int, String^>(2, "B") 
    }); 
}; 

int main() 
{ 
    for each (KeyValuePair<int, String^> kvp in CTest::ms_dict) 
    Console::WriteLine (kvp.Key.ToString() + " " + kvp.Value); 
} 

測試工作。