考虑下面的示例代码:“铸造”与反思
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;
}
现在我需要通过反射做同样的事情:
void SetValue(PropertyInfo info, object instance, object value)
{
// throws System.ArgumentException: Decimal can not be converted to Int64
info.SetValue(instance, value)
}
请注意,我不能假设的PropertyInfo始终代表长,那个值都不是小数。但是,我知道价值可以转换为该属性的正确类型。
我怎样才能在“值”参数转换为通过的PropertyInfo例如,通过反射表示的类型?
这个工作对我来说,很清楚的解释,谢谢 – 2017-11-10 01:13:48