数据模型类对比 反射c#

using System;
using System.ComponentModel.DataAnnotations;

 public class LoginModel
    {
       
        [Display(Name = "用户名")]
        public string UserName { get; set; }

        public string ExternalLoginData { get; set; }
    }
 /// <summary>
        /// 说明:对比实体类
        /// 时间:2014年2月20日 14:17:48
        /// Auhter:Kim
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="newModel"></param>
        /// <param name="oldModel"></param>
        /// <returns></returns>
        public string CompareModel<T>(T newModel, T oldModel) where T : class,new ()
        {
            StringBuilder strLog = new StringBuilder();
            System.Reflection. PropertyInfo[] mPi = typeof(T).GetProperties();
            for (int i = 0; i < mPi.Length; i++)
            {
                System.Reflection. PropertyInfo pi = mPi[i];
                string strName = string .Empty;
                string log=string .Empty;
                if (pi.GetValue(oldModel, null ) != null && pi.GetValue(newModel, null ) != null)
                {

                    strName = Attributes.GetDisplayInfo<T>(pi.Name);
                    string oldValue = pi.GetValue(oldModel, null).ToString();
                    string newValue = pi.GetValue(newModel, null).ToString();
                    if (oldValue != newValue)
                    {
                        if (GetNameByDictonary(strName, oldValue, newValue, out log))
                            strLog.Append(log);
                        else
                            strLog.AppendFormat("<strong>{0}</strong><span>{0} 从 {1} 改为 {2}</span>&nbsp;&nbsp;", strName, oldValue, newValue);
                    }
                }
            }
            return strLog.ToString();
        }


/// <summary>
        /// 获取DisplayInfo
        /// </summary>
        /// <param name="t"></param>
        public static string GetDisplayInfo<T>( string name) where T : class,new ()
        {
            Type objType = typeof (T);
            // Using reflection.
            string strName = string .Empty;
            PropertyInfo propInfo = objType.GetProperty(name);
            object[] attrs = propInfo.GetCustomAttributes(typeof (DisplayAttribute), true);  // Reflection.
            // Displaying output.
            if (attrs.Length > 0)
            {
                DisplayAttribute a = attrs[0] as DisplayAttribute;
                strName = a.Name;
            }

            return strName;
        }

原文地址:https://www.cnblogs.com/huhaihua/p/3664090.html