Wednesday, November 12, 2008 3:41 PM
Weird error that toke me a few autobot years to figure it out. Anyway, I got the following exception "System.Reflection.TargetException: Object does not match target type." when I tried to do some reflection, here is the code and off course as usual the error message wasn't descriptive enough.
foreach (object obj in this.InnerList)
{
System.Reflection.PropertyInfo pi = obj.GetType().GetProperty(field);
if (pi != null && pi.GetValue(obj,null).Equals(value))
return obj;
}
The above code simply locates an object within a collection that has a property/field "field" that matches the specified value "value" - kind of a find/search function. Here is the fix.
foreach (object obj in this.InnerList)
{
System.Reflection.PropertyInfo pi = obj.GetType().GetProperty(field);
if (pi != null && pi.GetValue(Activator.CreateInstance(obj.GetType()),
null).Equals(value))
return obj;
}
Can you spot the difference "Activator.CreateInstance", basically the "GetValue()" method needs an instance of the object and not the object itself, and why in the world was that not stated in the error message.