C# 适配 Maspter 不覆盖填充值

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);
    }
}
posted @ 2024-03-29 11:03  灵火  阅读(16)  评论(1编辑  收藏  举报