C# Using Reflection to Copy Base Class Properties

C# Using Reflection to copy base class properties

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

Using Reflection to copy across equivalent properties between struct and class

The starting point for all this is the System.Type class. You can get an instance of this for your type using e.GetType().

To look for a field, use GetField. If that returns null, then the field doesn't exist at all.

If it returns a value (of type FieldInfo) then use GetValue to get the value and SetValue to set it.

Reflection is relatively slow, so if performance is a concern, grab the System.Type object ahead of time with something like System.Type.getType(name) and also get the FieldInfo objects. You don't need the actual instance of the class to do either of those two operations, though obviously you need it to get and set the field values.

Copy class properties from class to a new subclass C#

You can use AutoMapper for that (or other mapping library):

var otherA = Mapper.Map<ClassA>(o_masterclass.ClassA);

By default it maps properties by name. So you even don't need to setup any configurations in this case.

In your solution you should pass sourceObject instead of it's type:

public static void CopyObject<T>(T sourceObject, ref T destObject)
{
if (sourceObject == null || destObject == null)
return;

// Get the type of each object
Type sourceType = sourceObject.GetType();
Type targetType = destObject.GetType();

// Loop through the source properties
foreach (PropertyInfo sourceProp in sourceType.GetProperties())
{
// Get the matching property in the destination object
PropertyInfo destProp = targetType.GetProperty(sourceProp.Name);
// If there is none, skip
if (destProp == null)
continue;

// Set the value in the destination
object value = sourceProp.GetValue(sourceObject, null);
destProp.SetValue(destObject, value, null);
}
}

And call it this way:

CopyObject<BaseClass>(o_masterclass.ClassA, ref instance);

Also keep in mind that type can contain indexers or read-only properties.

How to copy properties of a base class object to a child class object

You can use reflection to do this:

foreach (var field in typeof(AAA).GetFields())
{
field.SetValue(bbb, field.GetValue(aaa));
}

The idea is to loop through all the fields of type AAA in bbb and assign to them the values that they had in aaa. Note that this will only work for fields; if you want to also copy the values of properties, you can extend this to also use the .GetProperties() method.

Getting baseclass property value using reflection - base.Property as opposed to this.Property

It is possible, although as far as I know there's no way to do it without emitting your own IL, basically using the call instruction rather than callvirt.

Note that if you need to go to these lengths to make your design work then that's a sign that you're probably doing something wrong somewhere!

Anyway, here's a contrived example. (Error-checking etc omitted for brevity.)

var derived = new DerivedClass();
Console.WriteLine(derived.GetBaseProperty("Prop")); // displays "BaseProp"

// ...

public class BaseClass
{
public virtual string Prop { get; set;}
}

public class DerivedClass : BaseClass
{
public override string Prop { get; set;}

public DerivedClass()
{
base.Prop = "BaseProp";
this.Prop = "DerivedProp";
}

public object GetBaseProperty(string propName)
{
Type t = this.GetType();
MethodInfo mi = t.BaseType.GetProperty(propName).GetGetMethod();

var dm = new DynamicMethod("getBase_" + propName, typeof(object), new[] { typeof(object) }, t);

ILGenerator il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, mi);
if (mi.ReturnType.IsValueType) il.Emit(OpCodes.Box, mi.ReturnType);
il.Emit(OpCodes.Ret);

var getBase = (Func<object, object>)dm.CreateDelegate(typeof(Func<object, object>));
return getBase(this);
}
}


Related Topics



Leave a reply



Submit