如何根据类中属性的类型动态创建C#泛型词典?
我正在尝试根据以下类中的属性类型动态创建泛型词典:如何根据类中属性的类型动态创建C#泛型词典?,c#,.net,generics,dictionary,C#,.net,Generics,Dictionary,我正在尝试根据以下类中的属性类型动态创建泛型词典: public class StatsModel { public Dictionary<string, int> Stats { get; set; } } 因为我已经知道所创建的对象是一个泛型字典,所以我想将其转换为一个泛型字典,其类型参数等于属性类型的泛型参数: Type[] genericArguments = propertyType.GetGenericArguments(); // genericArgumen
public class StatsModel
{
public Dictionary<string, int> Stats { get; set; }
}
因为我已经知道所创建的对象是一个泛型字典,所以我想将其转换为一个泛型字典,其类型参数等于属性类型的泛型参数:
Type[] genericArguments = propertyType.GetGenericArguments();
// genericArguments contains two Types: System.String and System.Int32
Dictionary<?, ?> = (Dictionary<?, ?>)Activator.CreateInstance(propertyType);
Type[]genericArguments=propertyType.GetGenericArguments();
//genericArguments包含两种类型:System.String和System.Int32
Dictionary=(Dictionary)Activator.CreateInstance(propertyType);
这是可能的吗?如果要这样做,必须使用反射或
动态
转换为泛型方法,并使用泛型类型参数。否则,您必须使用对象
。就我个人而言,我只想在这里使用非通用的IDictionary
API:
// we know it is a dictionary of some kind
var data = (IDictionary)Activator.CreateInstance(propertyType);
这使您能够访问数据,以及您期望在字典中使用的所有常用方法(但是:使用object
)。转向通用方法是一种痛苦;要做到这一点,4.0之前的版本需要反射—特别是MakeGenericMethod
和Invoke
。但是,您可以在4.0中使用dynamic
:
dynamic dictionary = Activator.CreateInstance(propertyType);
HackyHacky(dictionary);
与:
void HackyHacky(字典数据){
TKey。。。
价值。。。
}
我一直在寻找常用的字典方法。我将投到IDictionary,特别是因为我不喜欢黑客;-)非常感谢你,马克!我得到:泛型类型“System.Collections.generic.IDictionary”需要2个类型arguments@tdc使用System.Collections添加代码>指令位于代码文件的顶部
dynamic dictionary = Activator.CreateInstance(propertyType);
HackyHacky(dictionary);
void HackyHacky<TKey,TValue>(Dictionary<TKey, TValue> data) {
TKey ...
TValue ...
}