60 lines
2.1 KiB
C#
60 lines
2.1 KiB
C#
|
|
|||
|
using AspectCore.Extensions.Reflection;
|
|||
|
using System.Reflection;
|
|||
|
namespace ZhiYi.Core.Application.Shared
|
|||
|
{
|
|||
|
public static class CustomerAppService
|
|||
|
{
|
|||
|
/// <summary>
|
|||
|
/// 自定义映射,默认值不映射
|
|||
|
/// </summary>
|
|||
|
/// <typeparam name="TSource"></typeparam>
|
|||
|
/// <typeparam name="TDest"></typeparam>
|
|||
|
/// <param name="source"></param>
|
|||
|
/// <param name="destination"></param>
|
|||
|
public static void ConditionalMap<TSource, TDest>(TSource source, TDest destination)
|
|||
|
where TSource : class
|
|||
|
where TDest : class
|
|||
|
{
|
|||
|
var sourceType = typeof(TSource);
|
|||
|
var destType = typeof(TDest);
|
|||
|
|
|||
|
foreach (var prop in sourceType.GetProperties())
|
|||
|
{
|
|||
|
var destProp = destType.GetProperty(prop.Name);
|
|||
|
if (destProp != null)
|
|||
|
{
|
|||
|
var defaultValue = prop.PropertyType.GetDefaultValue();
|
|||
|
var sourceValue = prop.GetValue(source);
|
|||
|
if (sourceValue != null && !sourceValue.Equals(defaultValue))
|
|||
|
{
|
|||
|
destProp.SetValue(destination, sourceValue);
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
/// <summary>
|
|||
|
/// 从所有字符串字段中删除前导和尾随空格.
|
|||
|
/// </summary>
|
|||
|
/// <typeparam name="T"></typeparam>
|
|||
|
/// <param name="obj"></param>
|
|||
|
public static void TrimStringFields<T>(this T obj) where T : class
|
|||
|
{
|
|||
|
if (obj is null) return;
|
|||
|
var stringProperties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
|
|||
|
.Where(p => p.PropertyType == typeof(string));
|
|||
|
|
|||
|
foreach (var property in stringProperties)
|
|||
|
{
|
|||
|
var propertyValue = (string?)property.GetValue(obj);
|
|||
|
if (propertyValue != null)
|
|||
|
{
|
|||
|
var trimmedValue = propertyValue.Trim();
|
|||
|
property.SetValue(obj, trimmedValue);
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
}
|