I have a property in a base class with some attributes on it:
[MyAttribute1]
[MyAttribute2]
public virtual int Count
{
get
{
// some logic here
}
set
{
// some logic here
}
}
In a deriving class I have done this, because I want to add MyAttribute3 to the property and I cannot edit the base class:
[MyAttribute3]
public override int Count
{
get
{
return base.Count;
}
set
{
base.Count = value;
}
}
However, the property is now behaving like it doesn't have MyAttribute1 and MyAttribute2 on it. Am I doing something wrong, or do attributes not inherit?
Attributes are not inherited by default. You can specify this using the AttributeUsage
attribute:
[AttributeUsage(AttributeTargets.Property, Inherited = true)]
public class MyAttribute : Attribute
{
}
It appears to work fine for me, if you're just using the method .GetType().GetCustomAttributes(true) this doesn't acually return any attributes, even if you set Inherited=true.
[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = true)]
sealed class MyAttribute : Attribute
{
public MyAttribute()
{
}
}
[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = true)]
sealed class MyAttribute1 : Attribute
{
public MyAttribute1()
{
}
}
class Class1
{
[MyAttribute()]
public virtual string test { get; set; }
}
class Class2 : Class1
{
[MyAttribute1()]
public override string test
{
get { return base.test; }
set { base.test = value; }
}
}
Then get the custom attributes from class 2.
Class2 a = new Class2();
MemberInfo memberInfo = typeof(Class2).GetMember("test")[0];
object[] attributes = Attribute.GetCustomAttributes(memberInfo, true);
attributes shows 2 elements in the array.
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