Files
Web_AuthorityManagement_Mvc…/Services/Extensions/ModelExtensions.cs

67 lines
2.3 KiB
C#
Raw Normal View History

2025-11-20 09:50:21 +08:00
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Services.Extensions
{
/// <summary>
/// 对象扩展
/// </summary>
public static class ModelExtensions
{
/// <summary>
/// 创建一个新的类型的对象,并将现有对象的属性值赋给新对象相同名称的属性
/// </summary>
/// <typeparam name="T">新对象的类型</typeparam>
/// <param name="source">现有对象</param>
/// <returns>新的对象</returns>
public static T ToModel<T>(this object source) where T : new()
{
if (source == null)
{
return default(T);
}
return Activator.CreateInstance<T>().UpdateFrom(source, new string[0]);
}
/// <summary>
/// 将源对象的属性值赋给目标对象相同名称的属性
/// </summary>
/// <typeparam name="T">目标类型</typeparam>
/// <param name="target">目标对象</param>
/// <param name="source">源对象</param>
/// <param name="copyPropertyName">需要复制的属性名,为空时表示复制全部</param>
/// <returns>目标类型</returns>
public static T UpdateFrom<T>(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;
}
}
}