Skip to content

Commit

Permalink
Add check
Browse files Browse the repository at this point in the history
  • Loading branch information
geoperez committed Sep 13, 2019
1 parent 6874e1f commit e2e77af
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions src/Swan.Lite/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public static int CopyOnlyPropertiesTo<T>(this T source, object target)
/// <returns>
/// Number of properties that were successfully copied.
/// </returns>
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);

/// <summary>
Expand Down Expand Up @@ -237,7 +237,7 @@ public static IEnumerable<string> GetCopyableProperties(this object @this)

return PropertyTypeCache.DefaultCache.Value
.RetrieveAllProperties(@this.GetType(), true)
.Select(x => new { x.Name, HasAttribute = AttributeCache.DefaultCache.Value.RetrieveOne<CopyableAttribute>(x) != null})
.Select(x => new { x.Name, HasAttribute = AttributeCache.DefaultCache.Value.RetrieveOne<CopyableAttribute>(x) != null })
.Where(x => x.HasAttribute)
.Select(x => x.Name);
}
Expand All @@ -259,7 +259,24 @@ public static IEnumerable<string> 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;
}
}
Expand Down

0 comments on commit e2e77af

Please sign in to comment.