属性定义
[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(); } }