C # Attribute inheritance not working as I would expect

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 the output class, I did 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 now behaves as if it does not have MyAttribute1 and MyAttribute2. Am I doing something wrong or not inheriting attributes?

+4
source share
2 answers

Attributes are not inherited by default. You can specify this using the AttributeUsage attribute:

 [AttributeUsage(AttributeTargets.Property, Inherited = true)] public class MyAttribute : Attribute { } 
+10
source

This seems to work fine for me if you just use the .GetType () method. GetCustomAttributes (true) this does not 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 custom attributes from class 2.

 Class2 a = new Class2(); MemberInfo memberInfo = typeof(Class2).GetMember("test")[0]; object[] attributes = Attribute.GetCustomAttributes(memberInfo, true); 

attributes show 2 elements in an array.

+2
source

Source: https://habr.com/ru/post/1415536/


All Articles