用反射“铸造" [英] 'casting' with reflection
本文介绍了用反射“铸造"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下示例代码:
class SampleClass
{
public long SomeProperty { get; set; }
}
public void SetValue(SampleClass instance, decimal value)
{
// value is of type decimal, but is in reality a natural number => cast
instance.SomeProperty = (long)value;
}
现在我需要通过反射做一些类似的事情:
Now I need to do something similar through reflection:
void SetValue(PropertyInfo info, object instance, object value)
{
// throws System.ArgumentException: Decimal can not be converted to Int64
info.SetValue(instance, value)
}
请注意,我不能假设 PropertyInfo 始终表示 long,该值也不总是小数.但是,我知道可以将值转换为该属性的正确类型.
Note that I cannot assume that the PropertyInfo always represents a long, neither that value is always a decimal. However, I know that value can be casted to the correct type for that property.
如何通过反射将'value'参数转换为PropertyInfo实例所代表的类型?
How can I convert the 'value' parameter to the type represented by PropertyInfo instance through reflection ?
推荐答案
void SetValue(PropertyInfo info, object instance, object value)
{
info.SetValue(instance, Convert.ChangeType(value, info.PropertyType));
}
这篇关于用反射“铸造"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文