using System; using System.Collections.Generic; using System.Reflection; using Newtonsoft.Json; namespace QYZH.InteractiveMagazine.Common.Extensions { /// /// 对象扩展方法 /// public static class ObjectExtension { /// /// 将源对象的属性值拷贝到目标对象 /// /// 目标对象类型 /// 源对象 /// 目标对象 /// 目标对象 public static T CopyTo(this object source, T target) { if (source == null || target == null) { return target; } Type sourceType = source.GetType(); Type targetType = target.GetType(); PropertyInfo[] sourceProperties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo sourceProp in sourceProperties) { if (!sourceProp.CanRead) { continue; } PropertyInfo? targetProp = targetType.GetProperty(sourceProp.Name); if (targetProp != null && targetProp.CanWrite && targetProp.PropertyType == sourceProp.PropertyType) { object? value = sourceProp.GetValue(source); targetProp.SetValue(target, value); } } return target; } /// /// 将对象转换为JSON字符串 /// /// 对象 /// 格式化选项 /// JSON字符串 public static string ToJson(this object obj, Formatting formatting = Formatting.None) { if (obj == null) { return string.Empty; } return JsonConvert.SerializeObject(obj, formatting); } /// /// 将对象转换为字典 /// /// 对象 /// 字典 public static Dictionary ToDictionary(this object obj) { if (obj == null) { return new Dictionary(); } var dictionary = new Dictionary(); PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (property.CanRead) { dictionary[property.Name] = property.GetValue(obj); } } return dictionary; } } }