From e2e77af7cd75060ce43c425f88f31b11d84a3b36 Mon Sep 17 00:00:00 2001 From: Geo Perez <1775792+geoperez@users.noreply.github.com> Date: Thu, 12 Sep 2019 21:59:38 -0500 Subject: [PATCH] Add check --- src/Swan.Lite/Extensions.cs | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/Swan.Lite/Extensions.cs b/src/Swan.Lite/Extensions.cs index 1e42514f2..75b3f7767 100644 --- a/src/Swan.Lite/Extensions.cs +++ b/src/Swan.Lite/Extensions.cs @@ -67,7 +67,7 @@ public static int CopyOnlyPropertiesTo(this T source, object target) /// /// Number of properties that were successfully copied. /// - public static int CopyOnlyPropertiesTo(this object source, object target, params string[] propertiesToCopy) + public static int CopyOnlyPropertiesTo(this object source, object target, params string[] propertiesToCopy) => ObjectMapper.Copy(source, target, propertiesToCopy); /// @@ -237,7 +237,7 @@ public static IEnumerable GetCopyableProperties(this object @this) return PropertyTypeCache.DefaultCache.Value .RetrieveAllProperties(@this.GetType(), true) - .Select(x => new { x.Name, HasAttribute = AttributeCache.DefaultCache.Value.RetrieveOne(x) != null}) + .Select(x => new { x.Name, HasAttribute = AttributeCache.DefaultCache.Value.RetrieveOne(x) != null }) .Where(x => x.HasAttribute) .Select(x => x.Name); } @@ -259,7 +259,24 @@ public static IEnumerable GetCopyableProperties(this object @this) target = Array.CreateInstance(elementType, sourceObjectList.Count); break; default: - target = Activator.CreateInstance(targetType, includeNonPublic); + var ctors = targetType.GetConstructors() + .Select(x => new { Ctor = x, Parameters = x.GetParameters() }) + .OrderBy(x => x.Parameters.Length); + + // Try to check if empty constructor is available + if (ctors.Any(x => x.Parameters.Length == 0)) + { + target = Activator.CreateInstance(targetType, includeNonPublic); + } + else + { + var firstCtor = ctors + .OrderBy(x => x.Parameters.Length) + .FirstOrDefault(); + + target = Activator.CreateInstance(targetType, firstCtor?.Parameters.Select(arg => arg.GetType().GetDefault()).ToArray()); + } + break; } }