Jer*_*oen 3 .net c# generics dictionary
我试图根据以下类中的属性类型动态创建泛型字典:
public class StatsModel
{
public Dictionary<string, int> Stats { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
假设Stats属性的System.Type被赋值给变量'propertyType',并且如果类型是泛型字典,则IsGenericDictionary方法返回true.然后我使用Activator.CreateInstance动态创建相同类型的通用Dictionary实例:
// Note: property is a System.Reflection.PropertyInfo
Type propertyType = property.PropertyType;
if (IsGenericDictionary(propertyType))
{
object dictionary = Activator.CreateInstance(propertyType);
}
Run Code Online (Sandbox Code Playgroud)
因为我已经知道创建的对象是一个通用字典,我想要转换为一个泛型字典,其类型参数等于属性类型的泛型参数:
Type[] genericArguments = propertyType.GetGenericArguments();
// genericArguments contains two Types: System.String and System.Int32
Dictionary<?, ?> = (Dictionary<?, ?>)Activator.CreateInstance(propertyType);
Run Code Online (Sandbox Code Playgroud)
这可能吗?
如果你想这样做,你将不得不使用反射或dynamic翻转到泛型方法,并使用泛型类型参数.没有它,你必须使用object.就个人而言,我在这里只使用非通用IDictionaryAPI:
// we know it is a dictionary of some kind
var data = (IDictionary)Activator.CreateInstance(propertyType);
Run Code Online (Sandbox Code Playgroud)
这使您可以访问数据,以及您希望在字典上使用的所有常用方法(但是:使用object).翻阅一般方法是一种痛苦; 做预先4.0需要反思-特别是MakeGenericMethod和Invoke.但是,您可以使用dynamic以下方法在4.0中作弊:
dynamic dictionary = Activator.CreateInstance(propertyType);
HackyHacky(dictionary);
Run Code Online (Sandbox Code Playgroud)
有:
void HackyHacky<TKey,TValue>(Dictionary<TKey, TValue> data) {
TKey ...
TValue ...
}
Run Code Online (Sandbox Code Playgroud)