zoukankan      html  css  js  c++  java
  • C#通过反射对可空类型动态赋值的问题

    C#通过反射对可空类型动态赋值的问题

    1. 转换成可空类型的基类型 
    2. object o = Convert.ChangeType( e.Value.ToString(), Nullable.GetUnderlyingType( type ) );
    3. 可以直接设置   值
    4.  recordCopy.GetType().GetProperty( gc.FieldName ).SetValue( recordCopy, o, null );

    假如有一个实体ProductInfo
    {
       pbulic System.Nullable<int> CategoryID{get; set;};
       .....
    }

    当使用反射得到CategoryID的PropertyInfo后
    Type type = typeOf(ProductInfo);
    PropetryInfo prop = type.GetProperties()[0];
    object instance = Activator.CreateInstance(type);
    prop.SetValue(instance, ChangeType(value, targetType),null);


    ChangeType方法如果是可空泛型,则获取其基本类型,例子中将转换成Int32。但在prop.SetValue的时候会报TargetInvocationException。
    显然,这里的Prop是int?,我该怎样把int?的类型通过反射给它赋进去?

     0 2012-01-06 13:55:42

    回复数 9 只看楼主 引用 举报 楼主

    你的代码没什么问题,除了pbulic ,PropetryInfo 别字{get; set;};多了分号

    建议检查下
    ChangeType(value, targetType)

    错误应该是这个方法里爆出来的

    0 2012-01-06 14:44:40

      

    Activator.CreateInstance(typeof(Nullable<>).MakeGenericType(typeof(int)));

  • 相关阅读:
    SpringBoot的缓存
    jsp标签指定id区域内容显示和隐藏
    Linux awk统计日志中出现过的IP(或出现次数最多的N个IP)
    回文数
    算法z形字符串
    最长回文字符串
    redis与Mysql数据同步
    算法(1)
    滑动窗口算法
    HTTP长连接和短连接
  • 原文地址:https://www.cnblogs.com/grj001/p/12223976.html
Copyright © 2011-2022 走看看