2013-07-07 42 views
2

說我有這樣的代碼:C#反射字典

Dictionary<String, String> myDictionary = new Dictionary<String, String>(); 
Type[] arguments = myDictionary.GetType().GetGenericArguments(); 

在我的程序,myDictionary它的未知類型(它是從反序列化XML返回的對象),但對於這個問題的目的,他們是字符串。我想創建這樣的東西:

Dictionary<arguments[0],arguments[1]> mySecondDictionary = new Dictionary<arguments[0],arguments[1]>(); 

很明顯,它不起作用。 我在MSDN上搜索,我看到他們正在使用Activator類,但我不明白。也許有人更先進,可以幫助我一點。

+1

請給你的問題一個有意義的標題。不要只列出標籤。這沒有任何意義,也不會吸引用戶查看並嘗試幫助您。 – abatishchev

+0

只需記下您最近刪除的問題。 [一切都已經發明](http://en.wikipedia.org/wiki/Charles_Holland_Duell) – paqogomez

回答

0

您可以使用像您提到的激活器類來創建給定類型的對象。 MakeGenericType方法允許您指定一個Types數組作爲通用對象的參數,這正是您試圖模擬的內容。

Dictionary<String, String> myDictionary = new Dictionary<String, String>(); 
Type[] arguments = myDictionary.GetType().GetGenericArguments(); 

Type dictToCreate = typeof(Dictionary<,>).MakeGenericType(arguments); 
var mySecondDictionary = Activator.CreateInstance(dictToCreate); 

上面的代碼是因爲你知道,字典是String,String預先但假設你有在運行時期間在別處檢測所需的類型,可以使用的最後兩行來實例化的一個詞典中的方式基本上無意義類型。

1

這種方法存在問題。 我會盡我所能解釋它。 我寫了一個程序,它首先將一個類序列化爲XML,然後將其反序列化。 基本上,它是一個通用的類,它包含一個List(與類相同的類型)。 因此,類的類型可以是任何類型,從簡單類型開始,如字符串,整型等等,到更復雜的類,例如書類或人物。在使用XmlSerializer.Deserialize方法並獲取對象之後,我應該使用Reflection來重建對象,並訪問列表。我不能那樣做。 所以,如果我有這樣的:

Type classToCreate = typeof(classToBeSerialized<>).MakeGenericType(arguments); 
var reconstructedClass = Activator.CreateInstance(classToCreate); 

其中classToBeSerialized它假定類(其中有我所講的列表),並returnedObject它的對象從XmlSerializer.Deserialize回來,我想訪問像這樣的列表:

((reconstructedClass)returnedObject).lista 

基本上,我使用反射來將對象轉換爲源代碼。

0

我知道這是一個古老的線程,但我只是需要類似的東西,並決定顯示它,(你知道谷歌)。

這是basicly通過@答案的重寫user2536272

public object ConstructDictionary(Type KeyType, Type ValueType) 
{ 
    Type[] TemplateTypes = new Type[]{KeyType, ValueType}; 
    Type DictionaryType = typeof(Dictionary<,>).MakeGenericType(TemplateTypes); 

    return Activator.CreateInstance(DictionaryType); 
} 

public void AddToDictionary(object DictionaryObject, object KeyObject, object ValueObject) 
{ 
    Type DictionaryType = DictionaryObject.GetType(); 

    if (!(DictionaryType .IsGenericType && DictionaryType .GetGenericTypeDefinition() == typeof(Dictionary<,>))) 
     throw new Exception("sorry object is not a dictionary"); 

    Type[] TemplateTypes = DictionaryType.GetGenericArguments(); 
    var add = DictionaryType.GetMethod("Add", new[] { TemplateTypes[0], TemplateTypes[1] }); 
    add.Invoke(DictionaryObject, new object[] { KeyObject, ValueObject }); 
}