【发布时间】:2012-01-18 09:39:26
【问题描述】:
我正在尝试根据以下类中的属性类型动态创建通用字典:
public class StatsModel
{
public Dictionary<string, int> Stats { get; set; }
}
假设将 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);
}
由于我已经知道创建的对象是通用字典,我想将其转换为类型参数等于属性类型的通用参数的通用字典:
Type[] genericArguments = propertyType.GetGenericArguments();
// genericArguments contains two Types: System.String and System.Int32
Dictionary<?, ?> = (Dictionary<?, ?>)Activator.CreateInstance(propertyType);
这可能吗?
【问题讨论】:
标签: c# .net generics dictionary