从基类访问应用于派生类中的方法的属性

时间:2008-11-10 19:19:52

标签: c# attributes custom-attributes

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

我这样做的最初计划是覆盖派生类中的方法,然后调用基本实现,此时应用所需的属性,如下所示:

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

这只打印“测试的基准值”,而不是我真正想要的其他值。

是否有人建议我如何修改它以获得所需的行为?

1 个答案:

答案 0 :(得分:7)

您明确反映了Base班级的GetAttributes方法。

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

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