我正在尝试基于以下类中的属性类型动态创建一个通用字典:
public class StatsModel
{
public Dictionary<string, int> Stats { get; set; }
}让我们假设Stats属性的System.Type被分配给一个变量'propertyType‘,并且如果该类型是一个泛型字典,则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);这个是可能的吗?
发布于 2012-01-18 17:49:52
如果要这样做,就必须使用反射或dynamic来转换为泛型方法,并使用泛型类型参数。如果没有它,你就必须使用object。就我个人而言,我在这里只使用非通用的IDictionary应用程序接口:
// 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,TValue>(Dictionary<TKey, TValue> data) {
TKey ...
TValue ...
}https://stackoverflow.com/questions/8907965
复制相似问题