我试图根据以下类中的属性类型动态创建泛型字典:
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)
这可能吗?