namespace XFEExtension.NetCore.ObjectExtension; /// /// 所有类的基类的拓展 /// public static class ObjectExtension { /// /// 进行浅拷贝 /// /// /// /// 浅拷贝后的对象 /// 无类型错误 public static T ActiveCopyOf(this T source) where T : class { return source is null ? throw new ArgumentNullException(nameof(source)) : (T)source.GetType().GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)?.Invoke(source, null)!; } /// /// 进行静态拷贝 /// /// /// /// 静态拷贝后的对象 public static T? StaticCopyOf(this T source) where T : class { if (source is null) { return default; } var fields = typeof(T).GetFields(); var properties = typeof(T).GetProperties(); var newObject = Activator.CreateInstance(); foreach (var property in properties) { property.SetValue(newObject, property.GetValue(source)); } foreach (var field in fields) { field.SetValue(newObject, field.GetValue(source)); } return newObject; } /// /// 比较两个对象的属性是否完全相同而非对象本身相同 /// /// /// /// /// public static bool AboutEqual(this T obj1, T obj2) { if (obj1 is null && obj2 is null) { return true; } if (obj1 is null || obj2 is null) { return false; } Type type = typeof(T); var properties = type.GetProperties(); var fields = type.GetFields(); foreach (var property in properties) { var value1 = property.GetValue(obj1); var value2 = property.GetValue(obj2); if (!Equals(value1, value2)) { return false; } } foreach (var field in fields) { var value1 = field.GetValue(obj1); var value2 = field.GetValue(obj2); if (!Equals(value1, value2)) { return false; } } return true; } }