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)));

  • 相关阅读:
    Selenium WebDriver-actionchain模拟键盘左键长按
    Selenium WebDriver-actionchain模拟鼠标右键操作
    CSS3 box-sizing:content-box | border-box
    gulp 使用指南
    MAC 使用指南
    移动端布局Rem
    JS面向对象编程
    webstorm 使用指南
    js 获取 touch length
    css 内容居中
  • 原文地址:https://www.cnblogs.com/grj001/p/12223977.html
Copyright © 2011-2022 走看看