public static class MapExtension
{
public static void Fill(this object src, object dest)
{
if (src == null || dest == null)
return;
var srcType = src.GetType();
var destType = dest.GetType();
var propertyInfos = srcType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.GetField);
var mapRules = TypeAdapterConfig.GlobalSettings.RuleMap.Values.SelectMany(z => z.Settings.Resolvers.Select(x => new
{
x.DestinationMemberName,
x.SourceMemberName
})).ToArray();
foreach (var propertyInfo in propertyInfos)
{
var destPropertyInfo = destType.GetProperty(propertyInfo.Name);
if (destPropertyInfo == null)
{
var destinationMemberName = mapRules.FirstOrDefault(x => x.SourceMemberName == propertyInfo.Name)?.DestinationMemberName;
if (destinationMemberName == null) continue;
destPropertyInfo = destType.GetProperty(destinationMemberName);
}
if (destPropertyInfo == null)
continue;
if (IsComplexObject(propertyInfo.PropertyType))
{
Fill(propertyInfo.GetValue(src), destPropertyInfo.GetValue(dest));
continue;
}
var value = propertyInfo.GetValue(src);
if (propertyInfo.PropertyType.IsValueType && value.Equals(GetDefaultValue(propertyInfo.PropertyType)))
continue;
if (value != null)
destPropertyInfo.SetValue(dest, value);
}
}
static bool IsComplexObject(Type type)
{
return !type.IsPrimitive && !type.IsEnum && type != typeof(string) && type != typeof(decimal);
}
static object GetDefaultValue(Type type)
{
return Activator.CreateInstance(type);
}
}
标签:C#,适配,destPropertyInfo,dest,Maspter,propertyInfo,var,null,type
From: https://www.cnblogs.com/fires/p/18103362