zoukankan      html  css  js  c++  java
  • .Net版的BeanUtils

    自己实现了Java的BeanUtils的部分功能,因为最近工作中用到了这个功能,以为.Net中也有类似Java的beanutils中的,网上找了半天没有找到相关的资源,记得以前实现过,可是使用中怕遇到了一些未知的问题,无耐之下自己动手实现了这个功能,下面是我实现,如有问题请指出:

    /**
     *@Author:wsx
     *@Date:2013-11-18
     *@Des:.Net实现Java的beanutils类
     */
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Collections;
    using System.Reflection;
    using System.Collections.Specialized;
    using System.Data;
    using System.Xml;
    
    namespace Com.Miteno.BeanUtils
    {
        public class BeanUtils
        {
            /// <summary>
            /// 将IDictionary赋值给bean对象
            /// </summary>
            /// <param name="bean"></param>
            /// <param name="properties"></param>
            public static void Populate(object bean, IDictionary properties)
            {
                IDictionaryEnumerator ide = properties.GetEnumerator();
                while (ide.MoveNext())
                {
                    SetProperty(bean, ide.Key.ToString(), ide.Value);
                }
            }
    
    
            /// <summary>
            /// 将IDictionary赋值给bean对象
            /// </summary>
            /// <param name="bean"></param>
            /// <param name="properties"></param>
            public static void Populate(object bean, IDictionary<string, object> properties)
            {
                foreach (string prop in properties.Keys)
                {
                    SetProperty(bean, prop, properties[prop]);
                }
            }
    
            /// <summary>
            /// 将NameValueCollection赋值给bean对象
            /// </summary>
            /// <param name="bean"></param>
            /// <param name="properties"></param>
            public static void Populate(object bean, NameValueCollection properties)
            {
                string[] keys = properties.AllKeys;
                foreach (string key in keys)
                {
                    SetProperty(bean, key, properties[key]);
                }
            }
    
    
            /// <summary>
            /// dr赋值给实例
            /// </summary>
            /// <param name="bean"></param>
            /// <param name="dr"></param>
            public static void Populate(object bean, DataRow dr)
            {
                IDictionary<string, object> dic = GetDictionary(dr);
                Populate(bean, dic);
            }
    
            /// <summary>
            /// dt得到实例
            /// </summary>
            /// <param name="bean"></param>
            /// <param name="dt"></param>
            /// <returns></returns>
            public static List<T> Populate<T>(T bean, DataTable dt)
            {
                List<T> l = new List<T>();
    
                List<IDictionary<string, object>> list = GetDictionary(dt);
                foreach (IDictionary dic in list)
                {
                    T cloneBean = Activator.CreateInstance<T>();
                    Populate(cloneBean, dic);
                    l.Add(cloneBean);
                }
    
                return l;
            }
    
            /// <summary>
            /// dt得到实例
            /// </summary>
            /// <param name="bean"></param>
            /// <param name="dt"></param>
            /// <returns></returns>
            public static List<T> Populate<T>(T bean, XmlDocument dom, string beanTagName, DomPropertyType propType)
            {
                List<T> l = new List<T>();
    
                List<IDictionary<string, object>> list = GetDictionary(dom, beanTagName, propType);
                foreach (IDictionary dic in list)
                {
                    T cloneBean = Activator.CreateInstance<T>();
                    Populate(cloneBean, dic);
                    l.Add(cloneBean);
                }
    
                return l;
            }
    
            /// <summary>
            /// 赋值bean
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="bean"></param>
            /// <returns></returns>
            public static T CloneBean<T>(T bean)
            {
                T o = Activator.CreateInstance<T>();
                CopyProperties(o, bean);
    
                return o;
            }
    
            public static void CopyProperties(object dest, object orig)
            {
                IDictionary cache = Describe(orig);
                Populate(dest, cache);
            }
    
            public static void CopyProperty(object bean, string name, object value)
            {
                SetProperty(bean, name, value);
            }
    
            public static IDictionary Describe(object bean)
            {
                Hashtable cache = new Hashtable();
                Type beantype = bean.GetType();
                PropertyInfo[] properties = beantype.GetProperties();
                foreach (PropertyInfo pi in properties)
                {
                    string pname = pi.Name;
                    object obj = pi.GetValue(bean, null);
                    cache.Add(pname, obj);
                }
    
                return cache;
            }
    
            /// <summary>
            /// 获取对象的属性
            /// </summary>
            /// <param name="bean"></param>
            /// <param name="props"></param>
            /// <returns></returns>
            public static IDictionary<string, object> GetDictionaryProperties(object bean, string[] props)
            {
                IDictionary<string, object> dic = new Dictionary<string, object>();
                foreach (string prop in props)
                {
                    object obj = GetProperty(bean, prop);
                    dic.Add(prop, obj);
                }
    
                return dic;
            }
    
            /// <summary>
            /// 获取对象的所有属性
            /// </summary>
            /// <param name="bean"></param>
            /// <returns></returns>
            public static IDictionary<string, object> GetAllProperties(object bean)
            {
                IDictionary<string, object> dic = new Dictionary<string, object>();
                Type type = bean.GetType();
                PropertyInfo[] pinfos = type.GetProperties();
                foreach (PropertyInfo pi in pinfos)
                {
                    dic.Add(pi.Name, pi.GetValue(bean, null));
                }
    
                return dic;
            }
    
            /// <summary>
            /// 获取对象指定的属性值
            /// </summary>
            /// <param name="bean">对象</param>
            /// <param name="name">属性名称</param>
            /// <returns></returns>
            public static object GetProperty(object bean, string name)
            {
                Type beantype = bean.GetType();
                PropertyInfo pi = beantype.GetProperty(name);
                return pi.GetValue(bean, null);
            }
    
            public static void SetProperty(object bean, string name, object value)
            {
                Type beantype = bean.GetType();
                PropertyInfo pi = beantype.GetProperty(name);
                object destValue = GetDestValue(pi, value);
                pi.SetValue(bean, destValue, null);
            }
    
            /// <summary>
            /// 获取值类型的默认值
            /// </summary>
            /// <returns></returns>
            private static object GetValueTypeDefaultValue(Type type)
            {
                object defValue;
                switch (type.FullName)
                {
                    case "System.Boolean":
                        defValue = false;
                        break;
                    case "System.Byte":
                    case "System.SByte":
                        defValue = Byte.MinValue;
                        break;
                    case "System.Int16":
                    case "System.UInt16":
                    case "System.Int32":
                    case "System.UInt32":
                    case "System.Int64":
                    case "System.UInt64":
                    case "System.Double":
                    case "System.Single":
                        defValue = Convert.ChangeType(0, type);
                        break;
                    case "System.Char":
                        defValue = '0';
                        break;
                    case "System.DateTime":
                        defValue = DateTime.MinValue;
                        break;
                    case "System.Decimal":
                        defValue = Convert.ChangeType(0, type);
                        break;
                    default:
                        defValue = 0;
                        break;
                }
    
                return defValue;
    
            }
    
            /// <summary>
            /// 获取类型的最终值
            /// </summary>
            /// <param name="pi"></param>
            /// <param name="value"></param>
            /// <returns></returns>
            private static object GetDestValue(PropertyInfo pi, object value)
            {
                Type propType = pi.PropertyType;
                if (propType.IsGenericType)
                {
                    //泛型类型(包括可空类型)
                    Type type = Nullable.GetUnderlyingType(propType);
                    if (type != null)
                    {
                        if (value == DBNull.Value)
                        {
                            value = null;
                        }
                        #region 作废该数据
                        //if (type.IsValueType)
                        //{
                        //    //值类型
                        //    if (value == DBNull.Value || value == null)
                        //    {
                        //        value = GetValueTypeDefaultValue(type);
                        //    }
                        //}
                        //else
                        //{
                        //    //引用类型
                        //    if (value == DBNull.Value)
                        //    {
                        //        value = null;
                        //    }
                        //}
                        #endregion
                    }
    
                }
                else
                {
                    if (propType.IsValueType)
                    {
                        //值类型
                        if (value == DBNull.Value || value == null)
                        {
                            value = GetValueTypeDefaultValue(propType);
                        }
                    }
                    else
                    {
                        //引用类型
                        if (value == DBNull.Value)
                        {
                            value = null;
                        }
                    }
                }
    
                return value;
            }
    
    
            /// <summary>
            /// 将DataRow转换成Hashtable
            /// </summary>
            /// <param name="row"></param>
            /// <returns></returns>
            public static IDictionary<string, object> GetDictionary(DataRow row)
            {
                IDictionary<string, object> dic = new Dictionary<string, object>();
                if (row != null)
                {
                    foreach (DataColumn c in row.Table.Columns)
                    {
                        dic.Add(c.ColumnName, row[c]);
                    }
                }
    
                return dic;
            }
    
    
            public static List<IDictionary<string, object>> GetDictionary(XmlDocument dom, string beanTagName, DomPropertyType propType)
            {
                List<IDictionary<string, object>> list = new List<IDictionary<string, object>>();
                switch (propType)
                {
                    case DomPropertyType.ElementType:
                        XmlNodeList nodes = dom.SelectNodes(string.Format(@"//" + beanTagName));
                        foreach (XmlNode xn in nodes)
                        {
                            IDictionary<string, object> dic = new Dictionary<string, object>();
                            XmlNodeList children = xn.ChildNodes;
                            foreach (XmlNode xnn in children)
                            {
                                dic.Add(xn.Name, xn.InnerText);
                            }
                            list.Add(dic);
                        }
                        break;
                    case DomPropertyType.AttributeType:
                        XmlNodeList ns = dom.SelectNodes(string.Format(@"//" + beanTagName));
                        foreach (XmlNode xn in ns)
                        {
                            IDictionary<string, object> dic = new Dictionary<string, object>();
                            XmlAttributeCollection attrs = xn.Attributes;
                            foreach (XmlAttribute attr in attrs)
                            {
                                dic.Add(attr.Name, attr.Value);
                            }
                            list.Add(dic);
                        }
                        break;
                    default: break;
                }
    
                return list;
            }
    
    
            /// <summary>
            /// 将DataTable转换成List<Hashtable>
            /// </summary>
            /// <param name="dt"></param>
            /// <returns></returns>
            public static List<IDictionary<string, object>> GetDictionary(DataTable dt)
            {
                List<IDictionary<string, object>> list = new List<IDictionary<string, object>>();
                if (dt != null)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        list.Add(GetDictionary(dr));
                    }
                }
    
                return list;
            }
    
            /// <summary>
            /// 将DataSet转成List
            /// </summary>
            /// <param name="ds"></param>
            /// <returns></returns>
            public static List<List<IDictionary<string, object>>> GetDictionary(DataSet ds)
            {
                List<List<IDictionary<string, object>>> list = new List<List<IDictionary<string, object>>>();
                if (ds != null && ds.Tables.Count > 0)
                {
                    list.Add(GetDictionary(ds.Tables[0]));
                }
    
                return list;
            }
        }
    
        /// <summary>
        /// 对象的值,是以节点的形式,还是以属性的形式
        /// </summary>
        public enum DomPropertyType
        {
            ElementType = 0, AttributeType = 1
        }
    }
  • 相关阅读:
    GNU KHATA——开源的会计管理软件
    Web服务精讲–搭个 Web 服务器(二)
    据说Linuxer都难忘的25个画面
    谷歌开源运作解密
    实战Centos系统部署Codis集群服务
    这些被称为史上最 “贱” 黑客
    Linux 利器- Python 脚本编程入门(一)
    在 Ubuntu 16.04 上安装 LEMP 环境之图文向导
    Linux下6种优秀的邮件传输代理
    移动互联网期末笔记
  • 原文地址:https://www.cnblogs.com/wangsx/p/3429645.html
Copyright © 2011-2022 走看看