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

但它有一个编译错误

我该怎么做?

4

1 回答 1

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);
        }
    }
}
于 2013-03-26T03:02:23.700 回答