“铸造”与反思 [英] 'casting' with reflection

查看:132
本文介绍了“铸造”与反思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的示例code:

 类SampleClass
{
    众长SomeProperty {搞定;组; }
}公共无效的SetValue(SampleClass例如,十进制值)
{
    //值的类型为小数,但在现实中是一个自然数=>投
    instance.SomeProperty =(长)值;
}

现在我需要做的通过反射类似的事情:

 无效的SetValue(的PropertyInfo信息,对象实例,对象的值)
{
    //抛出System.ArgumentException:小数不能转换为Int64的
    info.SetValue(例如,值)
}

请注意,我不能假设的PropertyInfo随时重新presents一个长期的,既没有值始终是一个小数。但是,我知道,值可以铸造到正确的类型,该属性。

我如何能在值参数转换为通过反射通过的PropertyInfo实例psented类型重新$ P $?


解决方案

 无效的SetValue(的PropertyInfo信息,对象实例,对象的值)
{
    info.SetValue(例如,Convert.ChangeType(值,info.PropertyType));
}

Consider the following sample code:

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

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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆