0
我想初始化泛型类型的所有公共属性。
我已经写了下面的方法:初始化通用类型中的所有属性?
public static void EmptyModel<T>(ref T model) where T : new()
{
foreach (PropertyInfo property in typeof(T).GetProperties())
{
Type myType = property.GetType().MakeGenericType();
property.SetValue(Activator.CreateInstance(myType));//Compile error
}
}
但它有一个编译错误
我该怎么办呢?
如果财产没有什么构造函数。例如:如果property为String,则发生此异常:'没有为此对象定义无参数构造函数。' – 2013-03-26 03:21:04
@Mohammad Activator.CreateInstance只适用于带无参数构造函数的类型(至少是您调用它的方式)。看到我的更新答案替代。这会使任何字符串属性初始化为null。 – 2013-03-26 03:34:01