|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Linq.Expressions; |
| 5 | +using System.Reflection; |
| 6 | + |
| 7 | +namespace Mapster |
| 8 | +{ |
| 9 | + public class DestinationTransform |
| 10 | + { |
| 11 | + public static readonly DestinationTransform EmptyCollectionIfNull = new DestinationTransform |
| 12 | + { |
| 13 | + Condition = type => type.IsArray |
| 14 | + || type.IsListCompatible() |
| 15 | + || type.GetDictionaryType() != null, |
| 16 | + TransformFunc = type => |
| 17 | + { |
| 18 | + Expression newExp; |
| 19 | + if (type.IsArray) |
| 20 | + { |
| 21 | + var rank = type.GetArrayRank(); |
| 22 | + var elemType = type.GetElementType()!; |
| 23 | + newExp = Expression.NewArrayBounds(elemType, Enumerable.Repeat(Expression.Constant(0), rank)); |
| 24 | + } |
| 25 | + else if (type.GetTypeInfo().IsInterface) |
| 26 | + { |
| 27 | + if (type.GetDictionaryType() != null) |
| 28 | + { |
| 29 | + var dict = type.GetDictionaryType()!; |
| 30 | + var dictArgs = dict.GetGenericArguments(); |
| 31 | + var dictType = typeof(Dictionary<,>).MakeGenericType(dictArgs); |
| 32 | + newExp = Expression.New(dictType); |
| 33 | + } |
| 34 | + else |
| 35 | + { |
| 36 | + var elemType = type.ExtractCollectionType(); |
| 37 | + var listType = typeof(List<>).MakeGenericType(elemType); |
| 38 | + newExp = Expression.New(listType); |
| 39 | + } |
| 40 | + } |
| 41 | + else |
| 42 | + newExp = Expression.New(type); |
| 43 | + |
| 44 | + var p = Expression.Parameter(type); |
| 45 | + return Expression.Lambda(Expression.Coalesce(p, newExp), p); |
| 46 | + } |
| 47 | + }; |
| 48 | + |
| 49 | + public static readonly DestinationTransform CreateNewIfNull = new DestinationTransform |
| 50 | + { |
| 51 | + Condition = type => |
| 52 | + { |
| 53 | + if (!type.CanBeNull()) |
| 54 | + return false; |
| 55 | + if (type.GetTypeInfo().IsInterface || type.GetTypeInfo().IsAbstract) |
| 56 | + return false; |
| 57 | + var ci = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).SingleOrDefault(c => c.GetParameters().Length == 0); |
| 58 | + return ci != null; |
| 59 | + }, |
| 60 | + TransformFunc = type => |
| 61 | + { |
| 62 | + var p = Expression.Parameter(type); |
| 63 | + return Expression.Lambda( |
| 64 | + Expression.Coalesce(p, Expression.New(type))); |
| 65 | + } |
| 66 | + }; |
| 67 | + |
| 68 | + public Func<Type, bool> Condition { get; set; } |
| 69 | + public Func<Type, LambdaExpression> TransformFunc { get; set; } |
| 70 | + |
| 71 | + public DestinationTransform WithCondition(Func<Type, bool> condition) |
| 72 | + { |
| 73 | + return new DestinationTransform |
| 74 | + { |
| 75 | + Condition = condition, |
| 76 | + TransformFunc = this.TransformFunc |
| 77 | + }; |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments