zoukankan      html  css  js  c++  java
  • Convert.ChangeType不能处理Nullable类型的解决办法(转)

    https://www.cnblogs.com/patrickyu/p/3211115.html

    在做一个ORMapping功能的时候发现,Convert.ChangeType不能处理nullable类型,比如int?.

    解决办法也很简单,贴出完整的代码(大部分代码来自网络),注意下面代码没经过完整测试,不要直接用在项目里:

     public delegate void SetValue<T>(T value);

       

    public static class ORMapping<T> where T : class, new()
        {
            private static Delegate CreateSetDelegate(T model, string propertyName)
            {
                MethodInfo mi = model.GetType().GetProperty(propertyName).GetSetMethod();
                //这里构造泛型委托类型
                Type delType = typeof(SetValue<>).MakeGenericType(GetPropertyType(propertyName));
                return Delegate.CreateDelegate(delType, model, mi);
            }
            private static Type GetPropertyType(string propertyName)
            {
                return typeof(T).GetProperty(propertyName).PropertyType;
            }
            
            public static IList<T> ConvertToBusinessEntityList(DataTable dt)
            {
                IList<T> list = new List<T>();
                if (dt == null || dt.Rows.Count < 1) return list;
                Delegate setDelegate;
                foreach (DataRow dr in dt.Rows)
                {
                    T model = new T();
                    foreach (DataColumn dc in dt.Columns)
                    {
                        setDelegate = CreateSetDelegate(model, dc.ColumnName);
                        Type type = GetPropertyType(dc.ColumnName);
                        Type underlyingType = Nullable.GetUnderlyingType(type);
                        if (DBNull.Value != dr[dc.ColumnName])
                        {
                            setDelegate.DynamicInvoke(Convert.ChangeType(dr[dc.ColumnName], underlyingType ?? type));
                        }
                    }
                    list.Add(model);
                }
                return list;
            }
        }

  • 相关阅读:
    线性表算法设计题2.11
    硬币抛掷模拟(使用数组)
    循环列示例(约瑟夫环问题)
    线性表算法设计题2.15
    ASP.NET2.0中的GRIDVIEW控件在使用TemplateField中的LinkButton时如何在RowCommand事件中找到当前行index的方法
    VS2005发布网站问题及"aspnet_merge.exe”已退出,代码为 1的错误
    弹出对话框的同时保持页面的显示(不变形)
    NET Framework 类库
    一些实用的正则表达式
    CuteEditor6.0使用配置心得体会
  • 原文地址:https://www.cnblogs.com/luluping/p/10182974.html
Copyright © 2011-2022 走看看