简体   繁体   中英

Accessing attributes applied to method in derived class from base class

So I've got a case where I'd like to be able to apply attributes to a (virtual) method in a derived class, but I'd like to be able to give a default implementation that uses those attributes in my base class.

My original plan for doing this was to override the method in the derived class and just call the base implementation, applying the desired attributes at this point, as follows:

public class Base {

    [MyAttribute("A Base Value For Testing")]
    public virtual void GetAttributes() {
        MethodInfo method = typeof(Base).GetMethod("GetAttributes");
        Attribute[] attributes = Attribute.GetCustomAttributes(method, typeof(MyAttribute), true);

        foreach (Attibute attr in attributes) {
            MyAttribute ma = attr as MyAttribute;
            Console.Writeline(ma.Value);
        }
    }
}

public class Derived : Base {

    [MyAttribute("A Value")]
    [MyAttribute("Another Value")]
    public override void GetAttributes() {
        return base.GetAttributes();
    }
}

This only prints "A Base Value For Testing", not the other values that I really want.

Does anybody have any suggestions as to how I can modify this to get the desired behavior?

You're explicitly reflecting the Base class's GetAttributes method.

Change the implementation to use GetType() , instead. As in:

public virtual void GetAttributes() {
    MethodInfo method = GetType().GetMethod("GetAttributes");
    // ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM