c# 对象反射赋值未知属性需类型转换

反射某个类时,对于类的属性,字段。已知有已知的方法,未知有未知的写法。

而SetValues赋值则需要类型转换

情况1,该属性类型是已知类型,例如:int

int value=500;
property.SetValue(obj,value,null);

  

这里需要注意value值的类型必须和属性类型一致,否则会抛出TargetException异常。

 

情况2,该属性类型是已知类型,原值是其他类型。例如:目标类型为int,值为string

string value="500";
property.SetValue(obj,int.TryParse(value),null);//类型转换

 

情况3,该属性类型是未知非泛型类型,不确定目标类型,如何进行类型转换

object value="500";
property.SetValue(obj,Convert.ChangeType(value,property.PropertyType),null);//类型转换

  

这是在非泛型情况,

若是泛型则加个判断吧

 1     if (!property.PropertyType.IsGenericType)
 2             {
 3                 //非泛型
 4                 property.SetValue(obj, string.IsNullOrEmpty(value) ? null : Convert.ChangeType(value, property.PropertyType), null);
 5             }
 6             else
 7             {
 8                 //泛型Nullable<>
 9                 Type genericTypeDefinition = property.PropertyType.GetGenericTypeDefinition();
10                 if (genericTypeDefinition == typeof(Nullable<>))
11                 {
12                     property.SetValue(obj, string.IsNullOrEmpty(value) ? null : Convert.ChangeType(value, Nullable.GetUnderlyingType(property.PropertyType)), null);
13                 }
14             }

 

贴个案例源代码:

1             var discount = "111";
2             Type t = obj.GetType();
3             PropertyInfo pi = t.GetProperty("discount");
4             if (pi != null)
5                 pi.SetValue(obj, Convert.ChangeType(discount, pi.PropertyType), null);

 

转载于:https://www.cnblogs.com/Zatsugaku-code/p/5761197.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值