From 53907b9c366c87c7d7c3e3f9cccc5c3f49a552ac Mon Sep 17 00:00:00 2001 From: Daniel Cronqvist Date: Thu, 5 Sep 2024 21:02:34 +0200 Subject: [PATCH] Add overload to MapPropertiesTo with supplied factory method --- src/DotTiled/Properties/IHasProperties.cs | 28 +++++++++++++++-------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/src/DotTiled/Properties/IHasProperties.cs b/src/DotTiled/Properties/IHasProperties.cs index 705a7d2..40c9853 100644 --- a/src/DotTiled/Properties/IHasProperties.cs +++ b/src/DotTiled/Properties/IHasProperties.cs @@ -38,6 +38,14 @@ public interface IHasProperties /// /// T MapPropertiesTo() where T : new(); + + /// + /// Maps all properties in this object to a new instance of the specified type using reflection. + /// + /// + /// + /// + T MapPropertiesTo(Func initializer); } /// @@ -78,15 +86,14 @@ public abstract class HasPropertiesBase : IHasProperties } /// - public T MapPropertiesTo() where T : new() - { - var properties = GetProperties(); - return CreateMappedInstance(properties); - } + public T MapPropertiesTo() where T : new() => CreateMappedInstance(GetProperties()); - private static object CreatedMappedInstance(Type type, IList properties) + /// + public T MapPropertiesTo(Func initializer) => CreateMappedInstance(GetProperties(), initializer); + + private static object CreatedMappedInstance(object instance, IList properties) { - var instance = Activator.CreateInstance(type) ?? throw new InvalidOperationException($"Failed to create instance of '{type.Name}'."); + var type = instance.GetType(); foreach (var prop in properties) { @@ -118,7 +125,7 @@ public abstract class HasPropertiesBase : IHasProperties break; case ClassProperty classProp: var subClassProp = type.GetProperty(prop.Name); - subClassProp?.SetValue(instance, CreatedMappedInstance(subClassProp.PropertyType, classProp.GetProperties())); + subClassProp?.SetValue(instance, CreatedMappedInstance(Activator.CreateInstance(subClassProp.PropertyType), classProp.GetProperties())); break; case EnumProperty enumProp: var enumPropInClass = type.GetProperty(prop.Name); @@ -133,5 +140,8 @@ public abstract class HasPropertiesBase : IHasProperties return instance; } - private static T CreateMappedInstance(IList properties) where T : new() => (T)CreatedMappedInstance(typeof(T), properties); + private static T CreateMappedInstance(IList properties) where T : new() => + (T)CreatedMappedInstance(Activator.CreateInstance() ?? throw new InvalidOperationException($"Failed to create instance of '{typeof(T).Name}'."), properties); + + private static T CreateMappedInstance(IList properties, Func initializer) => (T)CreatedMappedInstance(initializer(), properties); }