C#使用反射获取对象变化的情况
记录日志时, 经常需要描述对象的状态发生了怎样的变化, 以前处理的非常简单粗暴:
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#使用反射获取对象变化的情况的更多相关文章
- Java反射获取对象成员属性,getFields()与getDeclaredFields()方法的区别
Java反射获取对象成员属性,getFields()与getDeclaredFields()方法的区别 在工作中遇到一个问题,就是你需要去判断某个字符串是不是对象的某个成员属性名,然后根据判断结果 ...
- Java反射获取对象VO的属性值(通过Getter方法)
有时候,需要动态获取对象的属性值. 比如,给你一个List,要你遍历这个List的对象的属性,而这个List里的对象并不固定.比如,这次User,下次可能是Company. e.g. 这次我需要做一个 ...
- java利用反射获取对象前后修改的内容(用于日志记录)
import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Metho ...
- 第五课 JAVA反射获取对象属性和方法(通过配置文件)
Service1.java package reflection; public class Service1 { public void doService1(){ System.out.print ...
- C#通过反射获取对象属性,打印所有字段属性的值
获取所有字段的值: public void PrintProperties(Object obj) { Type type = obj.GetType(); foreach( PropertyInfo ...
- 第五课 JAVA反射获取对象属性和方法
package com.hero; import java.lang.reflect.Field; public class TestReflction5 { public static void m ...
- 利用反射获取对象中的值等于x的字段
Field[] field = behavior.getClass().getDeclaredFields(); for (int i = 0; i < field.length; i++) { ...
- c#利用反射获取对象属性值
public static string GetObjectPropertyValue<T>(T t, string propertyname){ Type type = type ...
- JAVA使用反射获取对象的所有属性名
public static void main(String[] args) { Field[] fields=BaseSalary.class.getDeclaredFields(); for (i ...
随机推荐
- JAVA 8 函数式接口--Consumer
从JDK8开始java支持函数式编程,JDK也提供了几个常用的函数式接口,这篇主要介绍Consumer接口.文本介绍的顺序依次为: 源码介绍 使用实例 jdk内对Consumer的典型使用 扩展类介绍 ...
- react基础学习 二——生命周期
生命周期mount: mounting装载创建 update更新 unmounting卸载 错误捕获 注意点:生命周期函数的 作用,什么之后用 只有类式组件有生命周期,函数式组件没有生命周期 moun ...
- 214. Spring Security:概述
前言 在之前介绍过了Shiro之后,有好多粉丝问SpringSecurity在Spring Boot中怎么集成.这个系列我们就和大家分享下有关这方面的知识. 本节大纲 一.什么是SpringSecur ...
- mysql 表
关系 create table scores( id int primary key auto_increment, stuid int, subid int, score decimal(5,2) ...
- 质心坐标(barycentric coordinates)及其应用
一.什么是质心坐标? 在几何结构中,质心坐标是指图形中的点相对各顶点的位置. 以图1的线段 AB 为例,点 P 位于线段 AB 之间, 图1 线段AB和点P 此时计算点 P 的公式为 . 同理,在三角 ...
- shiro初识
shiro 可以做认证.授权.加密.会话管理.与web集成.缓存. 在本文中,主要使用认证和授权这两个功能. 在shiro框架中,有些很重要的概念: Subject 很多人把它理解为当前用户,这 ...
- javaweb复习(一)
学习网站开发一般都是3部走.1.基本的servlet.jsp.js.html的内容学习.2.ssm.ssh之类的框架学习.3.大型网站开发的框架和技术学习(目前我还没学到),我学习这部分主要的书是李兴 ...
- dojo下的dom按钮与dijit/form/Button
众所周知,在dojo里存在dom和widget两个类型,dom指的是普通类型的HTML元素,包括各种类型的标签.按钮.输入框等等,而widget指的是dojo自身所带的模板,同时也包括按钮.输入框等等 ...
- nodeJs 控制台打印中文显示为Unicode解决方案
在使用 NodeJs 采集其他网站网页时遇到的,在获取源代码后发现里面原来的中文被转成了 Unicode(UTF8) 编码的中文(如:&# [xxx]),这当然不是真正想要的中文实体 解决方案 ...
- 38_redux_counter应用_react版本
redux的核心API 使用非redux创建: 项目结构: index.js import React from 'react'; import ReactDOM from 'react-dom'; ...