[英]Non-static method requires a target in PropertyInfo.SetValue
好的,所以我正在学习泛型,我正试图让这个东西运行,但它一直在说我同样的错误。 这是代码:
public static T Test<T>(MyClass myClass) where T : MyClass2
{
var result = default(T);
var resultType = typeof(T);
var fromClass = myClass.GetType();
var toProperties = resultType.GetProperties();
foreach (var propertyInfo in toProperties)
{
var fromProperty = fromClass.GetProperty(propertyInfo.Name);
if (fromProperty != null)
propertyInfo.SetValue(result, fromProperty, null );
}
return result;
}
发生这种情况是因为default(T)
返回null
因为T
表示引用类型。 引用类型的默认值为null
。
您可以将方法更改为:
public static T Test<T>(MyClass myClass) where T : MyClass2, new()
{
var result = new T();
...
}
然后它会按你的意愿工作。 当然, MyClass2
及其后代现在必须有一个无参数构造函数。
这里的问题是T
派生自MyClass
,因此是一个引用类型。 因此表达式default(T)
将返回值null
。 以下对SetValue的调用是操作一个null
值,但该属性是一个实例属性,因此您获得指定的消息。
您需要执行以下操作之一
T
实例传递给Test函数以设置属性值 代替
propertyInfo.SetValue(result, fromProperty, null);
尝试:
foreach (var propertyInfo in toProperties)
{
propertyInfo.GetSetMethod().Invoke(MyClass2, new object[]
{
MyClass.GetType().GetProperty(propertyInfo.Name).
GetGetMethod().Invoke(MyClass, null)
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.