c# – 通过反射设置属性Nullable <>

我尝试设置一个Nullable财产动态.

我得到我的财产ex:

PropertyInfo property = class.GetProperty("PropertyName"); // My property is Nullable<> at this time So the type Could be a string or int

我想通过反射来设置我的财产

property.SetValue(class,"1256",null);

当我的属性是Nullable<>时,它不起作用通用.所以我试图找到一种方式来设置我的财产.

要知道我的可空的<>的类型财产我执行

Nullable.GetUnderlyingType(property.PropertyType)

任何想法 ?

>我尝试创建一个我的Nullable<>财产与

var nullVar = Activator.CreateInstance(typeof(Nullable&)).MakeGenericType(new Type [] {Nullable.GetUnderlyingType(property.PropertyType)}));

但nullVar始终为空

解决方法

如果要将任意字符串转换为Nullable的底层类型,可以使用Convert类:
var propertyInfo = typeof(Foo).GetProperty("Bar");
object convertedValue = null;
try 
{ 
    convertedValue = System.Convert.ChangeType("1256",Nullable.GetUnderlyingType(propertyInfo.PropertyType));
} 
catch (InvalidCastException)
{
    // the input string Could not be converted to the target type - abort
    return;
}
propertyInfo.SetValue(fooInstance,convertedValue,null);

如果目标类型为int,short,long(或无符号变体,因为输入字符串表示非负数),double,float或decimal,则此示例将起作用.警告:这不是快速代码.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...