views:

417

answers:

1

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?

+7  A: 

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");
    // ...
Jacob Carpenter
That did it. Thanks!
Lawrence Johnston