微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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,则此示例将起作用.警告:这不是快速代码.

原文地址:https://www.jb51.cc/csharp/94333.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐