点滴积累,融会贯通

-----喜欢一切有兴趣的东西

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

属性定义

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class ColumnNameAttribute : Attribute
    {
        private string _columnName;
        public ColumnNameAttribute(string columnName, string columnChsName=null)
        {
            this._columnName = columnName;
            this._columnChsName = columnChsName;
        }

        public string ColumnName
        {
            get { return _columnName; }
        }

        private string _columnChsName;

        public string ColumnChsName
        {
            get { return _columnChsName; }
        }
    }

  属性使用

var properties = typeof(T).GetProperties().Where(v => v.IsDefined(typeof(ColumnNameAttribute), true)).ToList();

 foreach (var pro in properties)
            {
                var sourctValue = GetString(pro.GetValue(sourceObj, null));
                var newValue = GetString(pro.GetValue(newObj, null));
                if (sourctValue != newValue)
                {
                    string colName = ((ColumnNameAttribute)pro.GetCustomAttributes(typeof(ColumnNameAttribute), true)[0]).ColumnChsName;
                    logContent.AppendLine("</br>" + colName + ":从" + sourctValue + " 变更到 " + newValue);
                    hasChanged = true;
                }
            }

  私有方法

        private static string GetString(object o)
        {
            if (o == null || o== DBNull.Value)
            {
                return string.Empty;
            }
            else
            {
                return o.ToString();
            }
        }

  

posted on 2015-12-29 11:17  小寒  阅读(415)  评论(0编辑  收藏  举报