2010-03-02 76 views
3

我在C中++/CLI項目靜態數組的,如:是否可以在C++/CLI環境中創建靜態字典?

static array < array< String^>^>^ myarray= 
{ 
    {"StringA"}, 
    {"StringB"} 
}; 

是否有可能創建一個字典以同樣的方式? 我無法創建並初始化一個。

static Dictionary< String^, String^>^ myDic= 
{ 
    {"StringA", "1"}, 
    {"StringB", "2"} 
}; 

回答

2

在C#中,您的字典示例等稱爲Collection Initializer

您不能在C++/CLI中執行此操作。

// C# 3.0 
class Program 
{ 
    static Dictionary<int, string> dict = new Dictionary<int, string> 
    { 
     {1, "hello"}, 
     {2, "goodbye"} 
    }; 

    static void Main(string[] args) 
    { 
    } 
} 
0

我不知道CLI,但不應該二維數組得到你想要的東西很接近?

#include <iostream> 

int main() { 
    static int a[][3] = { {1, 2, 3}, {4, 5, 6}}; 
    std::cout << a[0][0] << " " << a[1][0]; 
    //.. 

} 
1

你不能在聲明中直接去做,但你可以使用一個靜態構造函數具有的靜態構造函數調用Add()方法做一次初始化。

0

雖然在C++不能創建一個std::map和初始化它像一個數組,則可以使用此構造加載在構造圖:

template <class InputIterator> 
    map (InputIterator first, InputIterator last, 
     const Compare& comp = Compare(), const Allocator& = Allocator()); 

一個替代方案是使用陣列和搜索方法如binary_search。如果數據沒有改變,這可能很有用。

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

另請參閱this Stackoverflow post。正如其他人所寫,在C++/CLI中不可能像使用C#那樣使用編譯器功能。
因此,我創建了一個小幫助函數(請參閱鏈接的文章),類似於@MrHIDEn的方法,但在他的解決方案中,他似乎使用了固定值。

相關問題