Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Using Reflection to copy base class properties

I would like to update all properties from MyObject to another using Reflection. The problem I am coming into is that the particular object is inherited from a base class and those base class property values are not updated.

The below code copies over top level property values.

public void Update(MyObject o) {     MyObject copyObject = ...      FieldInfo[] myObjectFields = o.GetType().GetFields(     BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);      foreach (FieldInfo fi in myObjectFields)     {         fi.SetValue(copyObject, fi.GetValue(o));     } } 

I was looking to see if there were any more BindingFlags attributes I could use to help but to no avail.

like image 536
David Avatar asked Jul 29 '09 08:07

David


1 Answers

Try this:

public void Update(MyObject o) {     MyObject copyObject = ...     Type type = o.GetType();     while (type != null)     {         UpdateForType(type, o, copyObject);         type = type.BaseType;     } }  private static void UpdateForType(Type type, MyObject source, MyObject destination) {     FieldInfo[] myObjectFields = type.GetFields(         BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);      foreach (FieldInfo fi in myObjectFields)     {         fi.SetValue(destination, fi.GetValue(source));     } } 
like image 75
maciejkow Avatar answered Oct 17 '22 18:10

maciejkow