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);
這可能嗎?
訪問常用的字典方法就是我一直在尋找。我會投向IDictionary,特別是因爲我不喜歡黑客;-)非常感謝Marc! – Jeroen 2012-01-18 13:39:19
我得到:泛型類型'System.Collections.Generic.IDictionary'需要2個類型參數 –
tdc
2013-05-09 10:01:33
@tdc在代碼文件頂部添加一個'using System.Collections;'指令 – 2013-05-09 10:03:48