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

Moh*_*yan 0 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
    }
}
Run Code Online (Sandbox Code Playgroud)

但它有一个编译错误

我该怎么做?

p.s*_*w.g 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)