2012-01-18 49 views
3

我試圖動態地創建基於屬性在下面的類類型的通用詞典:如何基於類中屬性的類型動態創建C#通用字典?

public class StatsModel 
{ 
    public Dictionary<string, int> Stats { get; set; } 
} 

假設屬性分配給一個變量「屬性類型」,而且統計的的System.Type如果類型是通用字典,則IsGenericDictionary方法返回true。然後我用Activator.CreateInstance動態地創建同一類型的通用詞典如:

// Note: property is a System.Reflection.PropertyInfo 
Type propertyType = property.PropertyType; 
if (IsGenericDictionary(propertyType)) 
{ 
    object dictionary = Activator.CreateInstance(propertyType); 
} 

因爲我已經知道了創建的對象是通用字典,我想轉換爲通用字典,它的類型參數等於屬性類型的一般參數:

Type[] genericArguments = propertyType.GetGenericArguments(); 
// genericArguments contains two Types: System.String and System.Int32 
Dictionary<?, ?> = (Dictionary<?, ?>)Activator.CreateInstance(propertyType); 

這可能嗎?

回答

5

如果你想這樣做,你必須使用反射或dynamic來翻轉成一個通用的方法,並使用泛型類型參數。沒有這個,你必須使用object。就個人而言,我只是使用非通用IDictionary API這裏:

// we know it is a dictionary of some kind 
var data = (IDictionary)Activator.CreateInstance(propertyType); 

,讓你訪問的數據,和所有常見的方法,您希望在一本字典(但:使用object)。轉變爲一種通用的方法是一種痛苦;要做到4.0之前需要反思 - 具體是MakeGenericMethodInvoke。你可以,但是,使用dynamic騙取4.0:

dynamic dictionary = Activator.CreateInstance(propertyType); 
HackyHacky(dictionary); 

有:

void HackyHacky<TKey,TValue>(Dictionary<TKey, TValue> data) { 
    TKey ... 
    TValue ... 
} 
+0

訪問常用的字典方法就是我一直在尋找。我會投向IDictionary,特別是因爲我不喜歡黑客;-)非常感謝Marc! – Jeroen 2012-01-18 13:39:19

+0

我得到:泛型類型'System.Collections.Generic.IDictionary '需要2個類型參數 – tdc 2013-05-09 10:01:33

+1

@tdc在代碼文件頂部添加一個'using System.Collections;'指令 – 2013-05-09 10:03:48