自定義屬性

屬性定義this

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

  屬性使用blog

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;
                }
            }

  私有方法ip

        private static string GetString(object o)
        {
            if (o == null || o== DBNull.Value)
            {
                return string.Empty;
            }
            else
            {
                return o.ToString();
            }
        }
相關文章
相關標籤/搜索