初始化通用类型中的所有属性?

时间:2013-03-26 02:59:05

标签: c# generics reflection

我想初始化泛型类型的所有公共属性 我写了以下方法:

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
    }
}

但它有编译错误

我该怎么办?

1 个答案:

答案 0 :(得分: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);
        }
    }
}
相关问题