加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:53:14 所属栏目:百科 来源:网络整理
导读:我尝试设置一个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,"
我尝试设置一个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,则此示例将起作用.警告:这不是快速的代码.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读