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);
}