码迷,mamicode.com
首页 > 其他好文 > 详细

自定义属性

时间:2015-12-29 12:27:37      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

属性定义

    [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();
            }
        }

  

自定义属性

标签:

原文地址:http://www.cnblogs.com/xh831213/p/5085060.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!