For some reason I'm not getting this. (Example model below) If I write:
var property = typeof(sedan).GetProperty("TurningRadius");
Attribute.GetCustomAttributes(property,typeof(MyAttribute), false)
the call will return MyAttribute(2) despite indicating I don't want to search the inheritance chain. Does anyone know what code I can write so that calling
MagicAttributeSearcher(typeof(Sedan).GetProperty("TurningRadius"))
returns nothing while calling
MagicAttributeSearcher(typeof(Vehicle).GetProperty("TurningRadius"))
returns MyAttribute(1)?
Example Model:
public class Sedan : Car
{
// ...
}
public class Car : Vehicle
{
[MyAttribute(2)]
public override int TurningRadius { get; set; }
}
public abstract class Vehicle
{
[MyAttribute(1)]
public virtual int TurningRadius { get; set; }
}
Okay, given the extra information - I believe the problem is that GetProperty is going up the inheritance change.
If you change your call to GetProperty to:
PropertyInfo prop = type.GetProperty("TurningRadius",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
then prop will be null if the property isn't overridden. For instance:
static bool MagicAttributeSearcher(Type type)
{
PropertyInfo prop = type.GetProperty("TurningRadius", BindingFlags.Instance |
BindingFlags.Public | BindingFlags.DeclaredOnly);
if (prop == null)
{
return false;
}
var attr = Attribute.GetCustomAttribute(prop, typeof(MyAttribute), false);
return attr != null;
}
This returns true and only if:
TurningRadius property (or declares a new one)MyAttribute attribute.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With