I have the following method that I can use to convert an object to a given type:
public static TTarget Convert<TTarget>(object source) where TTarget : new()
{
var target = new TTarget();
Type targetType = typeof (TTarget);
foreach (PropertyInfo sourceProperty in source.GetType().GetProperties())
{
if (!sourceProperty.CanRead || (sourceProperty.GetIndexParameters().Length > 0))
continue;
PropertyInfo targetProperty = targetType.GetProperty(sourceProperty.Name);
if ((targetProperty != null) && (targetProperty.CanWrite))
targetProperty.SetValue(target, sourceProperty.GetValue(source, null), null);
}
return target;
}
It works fine for simple classes with properties being value types and so on, but complex properties, that need to be mapped to another class, it's not quite clear how to go about it. If I store the mappings into a static property:
private static Dictionary<Type, Type> Mappings;
static TypeConverter()
{
Mappings = new Dictionary<Type, Type>
{
{typeof (DbSpace), typeof (DmsSpace)},
{typeof (DbDirectory), typeof (DmsDirectory)},
{typeof (DbFile), typeof (DmsFile)}
};
}
I don't seem to find a way to find a way to utilize this information for converting complex properties. How do I go about using the above mappings to convert complex properties?
The crux of the problem is: How can I call new if I only have a Type object?
Activator.CreateInstance(type), here's a link to msdn for those that think my answer was not "elaborate" enough (got 3 downvotes for a spot-on as-short-as-necessary answer)...
Have you also looked at AutoMapper?
You can use many serializers (JavaScriptSerializer, XmlSerializer, Json.Net etc.) to make a "deep convert" of your object as long as the propery names match.
I will give an example using JavaScriptSerializer
var class1 = new Class1() { Property = "a", SubProperty = new SubClass1() { SubProperty = "b" } };
var class2 = Convert<Class2>(class1);
public static TTarget Convert<TTarget>(object source) where TTarget : new()
{
var ser = new JavaScriptSerializer();
var json = ser.Serialize(source);
return ser.Deserialize<TTarget>(json);
}
.
public class Class1
{
public string Property { get; set; }
public SubClass1 SubProperty { get; set; }
}
public class SubClass1
{
public string SubProperty { get; set; }
}
public class Class2
{
public string Property { get; set; }
public SubClass2 SubProperty { get; set; }
}
public class SubClass2
{
public string SubProperty { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With