Files
DMS/Extensions/ObjectExtensions.cs

53 lines
2.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

namespace PMSWPF.Extensions;
public static class ObjectExtensions
{
/// <summary>
/// 对象转换将source对象上的所有属性的值都转换到target对象上
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
/// <typeparam name="T"></typeparam>
public static void CopyTo<T>(this object source, T target)
{
var sourceType = source.GetType();
var targetType = target.GetType();
var sourceProperties = sourceType.GetProperties();
foreach (var sourceProperty in sourceProperties)
{
var targetProperty = targetType.GetProperty(sourceProperty.Name);
if (targetProperty != null && targetProperty.CanWrite && sourceProperty.CanRead &&
targetProperty.PropertyType == sourceProperty.PropertyType)
{
var value = sourceProperty.GetValue(source, null);
targetProperty.SetValue(target, value, null);
}
}
}
/// <summary>
/// 创建一个泛型对象将source对象上的所有属性的值都转换到新创建对象上
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
/// <typeparam name="T"></typeparam>
public static T NewTo<T>(this object source) where T : new()
{
var target = new T();
var sourceType = source.GetType();
var targetType = target.GetType();
var sourceProperties = sourceType.GetProperties();
foreach (var sourceProperty in sourceProperties)
{
var targetProperty = targetType.GetProperty(sourceProperty.Name);
if (targetProperty != null && targetProperty.CanWrite && sourceProperty.CanRead &&
targetProperty.PropertyType == sourceProperty.PropertyType)
{
var value = sourceProperty.GetValue(source, null);
targetProperty.SetValue(target, value, null);
}
}
return target;
}
}