繁体   English   中英

如何使用反射来获取/设置属性值?

[英]How to use reflection to get/set the value of a property?

我试图使用反射来循环给定类中的所有属性,并对发现的所有DateTime属性执行转换。

但是,我收到一个错误{“对象与目标类型不匹配。”}

如何获取给定属性的值并设置其值?

我的代码:

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 
    }
}

问题似乎是您要传递给GetValue的参数-它必须是myObj ,而不是this

另外,您需要将调用的结果DateTime?DateTime? 分配:

DateTime? test = (DateTime?)prop.GetValue(this);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM