非静态方法需要 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;
}
Ok, so I'm learning about generics and I'm trying to make this thing run, but its keep saying me the same error. Here's the code:
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
发生这种情况是因为
default(T)
返回null
,因为T
表示引用类型。引用类型的默认值为null
。你可以将你的方法更改为:
然后它就会按照你想要的方式工作。当然,
MyClass2
及其后代现在必须有一个无参数构造函数。This happens because
default(T)
returnsnull
becauseT
represents a reference type. Default values for reference types arenull
.You could change your method to:
and then it will work as you want it to. Of course,
MyClass2
and its descendants must have a parameterless constructor now.这里的问题是
T
派生自MyClass
,因此是一个引用类型。因此表达式default(T)
将返回值null
。以下对 SetValue 的调用操作的是null
值,但该属性是实例属性,因此您会收到指定的消息。您需要执行以下操作之一
T
的真实实例传递给 Test 函数以设置属性值The problem here is that
T
derives fromMyClass
and is hence a reference type. So the expressiondefault(T)
will return the valuenull
. The following call to SetValue is operating an anull
value but the property is an instance property hence you get the specified message.You'll need to do one of the following
T
to the Test function to set the property values on而不是
尝试:
Instead of
try: