using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace AUTS.Services.Extensions { /// /// 对象扩展 /// public static class ModelExtensions { /// /// 创建一个新的类型的对象,并将现有对象的属性值赋给新对象相同名称的属性 /// /// 新对象的类型 /// 现有对象 /// 新的对象 public static T ToModel(this object source) where T : new() { if (source == null) { return default(T); } return Activator.CreateInstance().UpdateFrom(source, new string[0]); } /// /// 将源对象的属性值赋给目标对象相同名称的属性 /// /// 目标类型 /// 目标对象 /// 源对象 /// 需要复制的属性名,为空时表示复制全部 /// 目标类型 public static T UpdateFrom(this T target, object source, params string[] copyPropertyName) { if (target == null) { return default(T); } if (source == null) { return target; } Type typeFromHandle = typeof(T); foreach (PropertyInfo obj in source.GetType().GetProperties()) { //PropertyDescriptor propertyDescriptor = (PropertyDescriptor)obj; if (copyPropertyName == null || copyPropertyName.Length == 0 || copyPropertyName.Contains(obj.Name)) { PropertyInfo property = typeFromHandle.GetProperty(obj.Name, BindingFlags.Instance | BindingFlags.Public); if (property != null && property.CanWrite) { property.SetValue(target, obj.GetValue(source, null), null); } } } return target; } } }