I have written a class, for copying properties from one object to another, but I caught exception:
System.Reflection.TargetException: The object does not match the target type.
I checked, that fromPropValue is of correct type, is not null, etc.
Of course, property of recepient is Binary.
public class Reflector
{
public void ReflectProperties(object from, object to)
{
Type toType = to.GetType();
Type fromType = from.GetType();
var toProperties = toType.GetProperties();
foreach (var prop in toProperties)
{
var fromProp = fromType.GetProperty(prop.Name);
if (fromProp != null)
{
var propType = prop.PropertyType;
var fromPropValue = fromProp.GetValue(from, null);
if (propType == typeof(Binary))
prop.SetValue(this, (Binary)fromPropValue, null); // <-- error
else if (propType == typeof(string))
prop.SetValue(this, (string)fromPropValue, null);
else if (propType == typeof(bool))
prop.SetValue(this, (bool)fromPropValue, null);
}
}
}
}
P.S.: object from is parent of object to, and i want just to copy values of all properties from parent to child.
I think you want
prop.SetValue(to, ...instead ofprop.SetValue(this, ....Also you don’t need the
ifstatements and the casts. You can just doprop.SetValue(to, fromPropValue, null);