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)
但它有一个编译错误
我该怎么做?
这里有三个问题:
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)
| 归档时间: |
|
| 查看次数: |
1752 次 |
| 最近记录: |