2013-03-26 21 views
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 
    } 
} 

但它有一个编译错误

我该怎么办呢?

回答

5

有三个问题在这里:

  • PropertyInfo.SetValue有两个参数,一个引用的对象上设置属性(或null静态属性)',并设置它也值。
  • property.GetType()将返回PropertyInfo。要获取物业本身的类型,您需要改为使用property.PropertyType
  • 您的代码不处理属性类型上没有无参数构造函数的情况。如果没有彻底改变你做事的方式,你不能太想象,所以在我的代码中,如果没有找到无参数的构造函数,我将初始化属性为null

我想你要找的东西是这样的:

public static T EmptyModel<T>(ref T model) where T : new() 
{ 
    foreach (PropertyInfo property in typeof(T).GetProperties()) 
    { 
     Type myType = property.PropertyType; 
     var constructor = myType.GetConstructor(Type.EmptyTypes); 
     if (constructor != null) 
     { 
      // will initialize to a new copy of property type 
      property.SetValue(model, constructor.Invoke(null)); 
      // or property.SetValue(model, Activator.CreateInstance(myType)); 
     } 
     else 
     { 
      // will initialize to the default value of property type 
      property.SetValue(model, null); 
     } 
    } 
} 
+0

如果财产没有什么构造函数。例如:如果property为String,则发生此异常:'没有为此对象定义无参数构造函数。' – 2013-03-26 03:21:04

+1

@Mohammad Activator.CreateInstance只适用于带无参数构造函数的类型(至少是您调用它的方式)。看到我的更新答案替代。这会使任何字符串属性初始化为null。 – 2013-03-26 03:34:01