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

  • 相关阅读:
    [轉]推荐一个C#代码混淆器 .NET Reactor
    [转贴]什么是ORM
    十个极其有用的在线网站设计工具
    .NET Windows客户端程序在代理环境下的相关设置
    记4月28成都软件技术沙龙活动
    2010年仲夏成都.NET俱乐部活动——深度.NET
    在MOSS 2010上配置PDF的搜索【简译】
    在Windows 7中遇到android 模拟器出错,emulator: ERROR: unknown virtual device name的正确解决办法
    Visual Studio LightSwitch初体验和定位看法
    在.NET上进行线性代数等科学计算
  • 原文地址:https://www.cnblogs.com/luluping/p/10182974.html
Copyright © 2011-2022 走看看