I would like to create a function where I can pass in an arbitrary object and check to see if it has a specific property with a specific value. Im attempting to do this using reflection, but reflection still confuses me a little bit. I was hoping that someone might be able to point me in the right direction.
here is the code that im trying but obviously it doesnt work:
public static bool PropertyHasValue(object obj, string propertyName, string propertyValue)
{
try
{
if(obj.GetType().GetProperty(propertyName,BindingFlags.Instance).GetValue(obj, null).ToString() == propertyValue)
{
Debug.Log (obj.GetType().FullName + "Has the Value" + propertyValue);
return true;
}
Debug.Log ("No property with this value");
return false;
}
catch
{
Debug.Log ("This object doesnt have this property");
return false;
}
}
You will want to specify more
BindingFlagsin theType.GetPropertymethod call. You do this with a|character and the other flags, such asBindingFlags.Public. Other issues are not checking for nullobjparameter or null result from yourPropertyInfo.GetValuecall.To be more explicit in your method, you could write it like this and collapse down where you see fit.
In my opinion you should accept
propertyValueas anobjectand compare the objects equally, but that would exhibit a different behavior than your original sample.