jeudi 17 août 2017

"Object does not match target type" when calling SetValue from data obtained by GetValue

Variables source and target are two different instances of two different classes. But they both have an int property called ID.

Variables tProp and sProp are both PropertyInfo objects for the ID properties on their respective objects.

sProp has value 54, and the IDE Locals windwows shows it as type obj{int}

tProp is a valid property, not set yet.

I am trying to set target.ID using this code:

var sVal = sProp.GetValue(source);
tProp.SetValue(target, sVal);

When I hit that line I get "Object does not match target type".

I know that I can fix this by casting sVal to int, but I'm trying to write generic code here, and thought that at least .NET would be able to determine that the two objects are exactly the same type. Am I missing something?

Any idea how to solve this, other than checking types and casting?





Aucun commentaire:

Enregistrer un commentaire