4

所以我有一个案例,我希望能够将属性应用于派生类中的(虚拟)方法,但我希望能够提供一个在我的基类中使用这些属性的默认实现.

我最初的计划是重写派生类中的方法并只调用基本实现,此时应用所需的属性,如下所示:

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();
    }
}

这只会打印“A Base Value For Testing”,而不是我真正想要的其他值。

有人对我如何修改它以获得所需的行为有任何建议吗?

4

1 回答 1

7

你明确地反映了Base类的GetAttributes方法。

将实现改为使用GetType()。如:

public virtual void GetAttributes() {
    MethodInfo method = GetType().GetMethod("GetAttributes");
    // ...
于 2008-11-10T19:25:39.153 回答