[英]How to use reflection to get/set the value of a property?
I am trying to use reflection to cycle through all of the properties in a given class and perform a conversion on all DateTime properties it finds. 我试图使用反射来循环给定类中的所有属性,并对发现的所有DateTime属性执行转换。
However I am getting an error {"Object does not match target type."} 但是,我收到一个错误{“对象与目标类型不匹配。”}
How do I get the value of the given property and set its value? 如何获取给定属性的值并设置其值?
My code: 我的代码:
var properties = myObj.GetType().GetProperties();
foreach (var prop in properties) {
if (prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(DateTime?)) {
DateTime? test = prop.GetValue(this);
// Do conversion on test
// Do something like prop.SetValue(??) with the new value
}
}
The problem appears to be the parameter that you are passing to GetValue
- it needs to be myObj
, not this
. 问题似乎是您要传递给GetValue
的参数-它必须是myObj
,而不是this
。
In addition, you need to cast the result of the call to DateTime?
另外,您需要将调用的结果DateTime?
为DateTime?
on assignment: 分配:
DateTime? test = (DateTime?)prop.GetValue(this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.