对像相同赋值

来源:互联网 发布:如何下载英语软件 编辑:程序博客网 时间:2024/06/11 18:31

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace BMW.Core.Common
{
    public class ObjectUtils
    {
        public static List<string> CopyProperties(object src, object target)
        {
            return CopyProperties(src, target, null);
        }
        public static List<string> CopyProperties(object src, object target, string[] excludeProperties)
        {
            return CopyProperties(src, target, excludeProperties, true);
        }
        public static List<string> CopyProperties(object src, object target, string[] excludeProperties, bool ignoreCase)
        {
            List<string> copyList = new List<string>();
            Type srcType=src.GetType();
            Type tarType = target.GetType();
            Dictionary<string, PropertyInfo> srcDic = new Dictionary<string, PropertyInfo>();
            foreach (PropertyInfo info in srcType.GetProperties())
                srcDic.Add(ignoreCase?info.Name.ToLower():info.Name,info);
            if (excludeProperties != null)
            {
                foreach (string notKey in excludeProperties)
                    srcDic.Remove(ignoreCase ? notKey.ToLower() : notKey);
            }
            foreach (PropertyInfo tarInfo in tarType.GetProperties())
            {
                if (!tarInfo.CanWrite)
                    continue;
               
                string key=ignoreCase?tarInfo.Name.ToLower():tarInfo.Name;
                if (srcDic.ContainsKey(key))
                {
                    PropertyInfo srcInfo = srcDic[key];
                    try
                    {
                        tarInfo.SetValue(target, srcInfo.GetValue(src, null), null);
                    }
                    catch (Exception ex)
                    {
                        throw new FormatException(string.Format("源对象的{0}属性类型为{1},不能成功转换为目标对象的{2}属性的{3}类型,请调整.",
                            srcInfo.Name, srcInfo.PropertyType.Name, tarInfo.Name, tarInfo.PropertyType),ex);
                    }
                    copyList.Add(tarInfo.Name);
                }
            }
            return copyList;
        }
    }
}

原创粉丝点击