记录日志时, 经常需要描述对象的状态发生了怎样的变化, 以前处理的非常简单粗暴:

  a. 重写class的ToString()方法, 将重要的属性都输出来

  b. 记录日志时:  谁谁谁  由  变更前实例.ToString()   变成   变更后实例.ToString()

  但输出的日志总是太长了, 翻看日志时想找到差异也非常麻烦, 所以想输出为:  谁谁谁的哪个属性由  aaa 变成了 bbb

  手写代码一个一个的比较字段然后输出这样的日志信息, 是不敢想象的事情. 本来想参考Dapper使用 System.Reflection.Emit 发射 来提高运行效率, 但实在没有功夫研究.Net Framework的中间语言, 所以准备用 Attribute特性 和 反射 来实现

/// <summary>
/// 要比较的字段或属性, 目前只支持C#基本类型, 比如 int, bool, string等, 你自己写的class或者struct 需要重写 ToString()、Equals(), 按理说如果重写了Equals(), 那也需要重写GetHashCode(), 但确实没有用到GetHashCode(), 所以可以忽略Warning不重写GetHashCode();
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
public class ComparePropertyFieldAttribute : Attribute
{
/// <summary>
/// 属性或字段的别名
/// </summary>
public string PropertyName { get; private set; } /// <summary>
/// 要比较的字段或属性
/// </summary>
public ComparePropertyFieldAttribute()
{ } /// <summary>
/// 要比较的字段或属性
/// </summary>
/// <param name="propertyName">属性或字段的别名</param>
public ComparePropertyFieldAttribute(string propertyName)
{
PropertyName = propertyName;
} // 缓存反射的结果, Tuple<object, ComparePropertyAttribute> 中第一个参数之所以用object 是因为要保存 PropertyInfo 和 FieldInfo
private static Dictionary<Type, Tuple<object, ComparePropertyFieldAttribute>[]> dict = new Dictionary<Type, Tuple<object, ComparePropertyFieldAttribute>[]>(); /// <summary>
/// 只对带有ComparePropertyAttribute的属性和字段进行比较
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="from"></param>
/// <param name="to"></param>
/// <param name="differenceMsg">不相同的字段或属性 的字符串说明</param>
/// <returns>两者相同时, true; 两者不相同时, false</returns>
public static bool CompareDifference<T>(T from, T to, out string differenceMsg)
{
var type = typeof(T);
lock (dict)
{
if (!dict.ContainsKey(type))
{
var list = new List<Tuple<object, ComparePropertyFieldAttribute>>();
// 获取带ComparePropertyAttribute的属性
var properties = type.GetProperties();
foreach (var property in properties)
{
var comparePropertyAttribute = (ComparePropertyFieldAttribute)property.GetCustomAttributes(typeof(ComparePropertyFieldAttribute), false).FirstOrDefault();
if (comparePropertyAttribute != null)
{
list.Add(Tuple.Create<object, ComparePropertyFieldAttribute>(property, comparePropertyAttribute));
}
}
// 获取带ComparePropertyAttribute字段
var fields = type.GetFields();
foreach (var field in fields)
{
var comparePropertyAttribute = (ComparePropertyFieldAttribute)field.GetCustomAttributes(typeof(ComparePropertyFieldAttribute), false).FirstOrDefault();
if (comparePropertyAttribute != null)
{
list.Add(Tuple.Create<object, ComparePropertyFieldAttribute>(field, comparePropertyAttribute));
}
} dict.Add(type, list.ToArray());
}
} var sb = new StringBuilder(); //估计200字节能覆盖大多数情况了吧
var tupleArray = dict[type];
foreach (var tuple in tupleArray)
{
object v1 = null, v2 = null;
if (tuple.Item1 is System.Reflection.PropertyInfo)
{
if (from != null)
{
v1 = ((System.Reflection.PropertyInfo)tuple.Item1).GetValue(from, null);
}
if (to != null)
{
v2 = ((System.Reflection.PropertyInfo)tuple.Item1).GetValue(to, null);
}
if (!object.Equals(v1, v2))
{
sb.AppendFormat("{0}从 {1} 变成 {2}; ", tuple.Item2.PropertyName ?? ((System.Reflection.PropertyInfo)tuple.Item1).Name, v1 ?? "null", v2 ?? "null");
}
}
else if (tuple.Item1 is System.Reflection.FieldInfo)
{
if (from != null)
{
v1 = ((System.Reflection.FieldInfo)tuple.Item1).GetValue(from);
}
if (to != null)
{
v2 = ((System.Reflection.FieldInfo)tuple.Item1).GetValue(to);
}
if (!object.Equals(v1, v2))
{
sb.AppendFormat("{0}从 {1} 变成 {2}; ", tuple.Item2.PropertyName ?? ((System.Reflection.FieldInfo)tuple.Item1).Name, v1 ?? "null", v2 ?? "null");
}
}
} differenceMsg = sb.ToString();
return differenceMsg == "";
}
}

ComparePropertyFieldAttribute

  使用方法:

  1. 将重要字段或属性加上 [ComparePropertyField] 特性, 目前只支持C#基本类型, 比如 int, bool, string等, 你自己写的class或者struct 需要重写 ToString()、Equals(), 按理说如果重写了Equals(), 那也需要重写GetHashCode(), 但确实没有用到GetHashCode(), 所以可以忽略Warning不重写GetHashCode()

  2. 使用ComparePropertyFieldAttribute.CompareDifference 比较变更前后的实例即可

  具体可参考下面的示例

class Program
{
static void Main(string[] args)
{
// 请用Debug测试, Release会优化掉一些代码导致测试不准确
System.Diagnostics.Stopwatch stopwatch = new Stopwatch();
var p1 = new Person() { INT = , BOOL = false, S = "p1", S2 = "p1" };
var p2 = new Person() { INT = , BOOL = false, S = "p1", S2 = "p1" };
string msg = null; stopwatch.Start();
for (int i = ; i < ; i++)
{
if (!p1.Equals(p2))
{
msg = string.Format("{0} 变成 {1}", p1.ToString(), p2.ToString());
}
}
stopwatch.Stop();
Console.WriteLine("原生比较结果: " + msg);
Console.WriteLine("原生比较耗时: " + stopwatch.Elapsed); stopwatch.Start();
for (int i = ; i < ; i++)
{
var result = ComparePropertyFieldAttribute.CompareDifference<Person>(p1, p2, out msg);
}
stopwatch.Stop();
Console.WriteLine("ComparePropertyAttribute比较结果: " + msg);
Console.WriteLine("ComparePropertyAttribute比较: " + stopwatch.Elapsed); Console.ReadLine();
}
} public class Person
{
[ComparePropertyField]
public int INT { get; set; } [ComparePropertyFieldAttribute("布尔")]
public bool BOOL { get; set; } [ComparePropertyFieldAttribute("字符串")]
public string S { get; set; } [ComparePropertyFieldAttribute("S22222")]
public string S2; public override bool Equals(object obj)
{
var another = obj as Person;
if (another==null)
{
return false;
}
return this.INT == another.INT &&
this.BOOL == another.BOOL &&
this.S == another.S &&
this.S2 == another.S2;
} public override string ToString()
{
return string.Format("i={0}, 布尔={1}, 字符串={2}, S22222={3}", INT, BOOL, S, S2);
}
}

耗时是原生的3倍, 考虑到只有记录日志才使用这个, 使用的机会很少, 对性能的损耗可以认为非常小.

  end

  

C#使用反射获取对象变化的情况的更多相关文章

  1. Java反射获取对象成员属性,getFields()与getDeclaredFields()方法的区别

    Java反射获取对象成员属性,getFields()与getDeclaredFields()方法的区别 ​ 在工作中遇到一个问题,就是你需要去判断某个字符串是不是对象的某个成员属性名,然后根据判断结果 ...

  2. Java反射获取对象VO的属性值(通过Getter方法)

    有时候,需要动态获取对象的属性值. 比如,给你一个List,要你遍历这个List的对象的属性,而这个List里的对象并不固定.比如,这次User,下次可能是Company. e.g. 这次我需要做一个 ...

  3. java利用反射获取对象前后修改的内容(用于日志记录)

    import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Metho ...

  4. 第五课 JAVA反射获取对象属性和方法(通过配置文件)

    Service1.java package reflection; public class Service1 { public void doService1(){ System.out.print ...

  5. C#通过反射获取对象属性,打印所有字段属性的值

    获取所有字段的值: public void PrintProperties(Object obj) { Type type = obj.GetType(); foreach( PropertyInfo ...

  6. 第五课 JAVA反射获取对象属性和方法

    package com.hero; import java.lang.reflect.Field; public class TestReflction5 { public static void m ...

  7. 利用反射获取对象中的值等于x的字段

    Field[] field = behavior.getClass().getDeclaredFields(); for (int i = 0; i < field.length; i++) { ...

  8. c#利用反射获取对象属性值

    public static string GetObjectPropertyValue<T>(T t, string propertyname){     Type type = type ...

  9. JAVA使用反射获取对象的所有属性名

    public static void main(String[] args) { Field[] fields=BaseSalary.class.getDeclaredFields(); for (i ...

随机推荐

  1. java异常处理——finally相关

    示例程序1 public class EmbededFinally { public static void main(String args[]) { int result; try { Syste ...

  2. 为什么vue支持IE9以上的IE浏览器?

    原因如下: 1.vue框架中核心的双向绑定原理是利用Object.defineProperty()方法实现的. 2.该方法第一个被实现是在IE8中,但是存在诸多限制:只能在DOM对象上使用这个方法,而 ...

  3. spring suite tool 添加namespace时只有bean一个

    在eclipse的windows->Preferences->Spring->Beans Support->Namespaces 在此记录此问题.

  4. SockJS

    1\ 2\ 下载

  5. tornado架构分析3 options.py中基础类_Option

    1 数据清洗 option里面最重要的方法就是parse,在这里,parse函数的一开始就调用了后面的子函数_parse_datetime,_parse_timedelta,_parse_bool,_ ...

  6. 深入理解Java虚拟机读书笔记5----虚拟机字节码执行引擎

    五 虚拟机字节码执行引擎   1 运行时栈帧结构     ---栈帧是用于支持虚拟机进行方法调用和方法执行的数据结构,是虚拟机运行时数据区中的虚拟机栈的栈元素.     ---栈帧中存储了方法的局部变 ...

  7. 进制与进制转换DAY2

    进制和进制转换 一.进制的基础 1.十进制(案例) 系数:0-9 进位规则:逢十进一 权:基数的次幂 基数:几进制基数就是几 规律:右侧第一位的权是10的0次幂,每向左移动一位次幂会+1. 进制的表示 ...

  8. python_14 静态属性、类方法、静态方法;组合;继承

    静态属性 在类中函数前加@property,在实例调用函数时无需加(),将函数属性封装,调用时看起来与数据属性类似 将函数封装成数据属性的形式,外部调用时看不到逻辑,静态属性可以访问实例属性也可以访问 ...

  9. jsfl 进入影片 退出影片

    targetMC=fl.getDocumentDOM().getTimeline().layers [0].frames[0].elements[0]; fl.getDocumentDOM().lib ...

  10. eclipse与idea快捷键对比以及idea debug、git快捷键

    eclipse与idea快捷键 表格中的空格都是忘记了~ 功能 eclipse idea 生成返回值对象 alt+shift+L ctrl+alt+V 找到启动类   ctrl+alt+Home 类的 ...