For the question, https://stackoverflow.com/a/312799/16/163899/ ... I recently wrote a universal extension method that should load an object from another, i.e. assign all the properties of the target source and therefore do it recursively if the property is a reference. I used reflection quite far, but I ran into a problem when it comes to property types that are reference types, here is my first approach:
First approach:
public static void Load<T>(this T target, T source, bool deep) { foreach (PropertyInfo property in typeof(T).GetProperties()) { if (property.CanWrite && property.CanRead) { if (!deep || property.PropertyType.IsPrimitive || property.PropertyType == typeof(String)) { property.SetValue(target, property.GetValue(source, null), null); } else { property.GetValue(target, null).Load(property.GetValue(source, null), deep); } } } }
The problem is that PropertyInfo.GetValue returns an object, subsequently T will be equal to object in the recursive call, and I can no longer get the properties that the object actually has.
I came up with a workaround that requires you to explicitly specify a type that is pretty redundant, since theoretically you can do without it:
public static void Load<T>(this T target, Type type, T source, bool deep) { foreach (PropertyInfo property in type.GetProperties()) { if (property.CanWrite && property.CanRead) { if (!deep || property.PropertyType.IsPrimitive || property.PropertyType == typeof(String)) { property.SetValue(target, property.GetValue(source, null), null); } else { object targetPropertyReference = property.GetValue(target, null); targetPropertyReference.Load(targetPropertyReference.GetType(), property.GetValue(source, null), deep); } } } }
I also tried using dynamic targetPropertyReference , but then I get an exception at runtime that the Load method cannot be found, it infuriates.
In addition, Convert.ChangeType also returns a damn object too, and I cannot otherwise render the object as it is. Of course, I searched for the answer to this on the net, but so far I have not been successful.