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

これは、「テストの基本値」のみを出力し、本当に必要な他の値は出力しません。

これを変更して目的の動作を得る方法について、誰か提案はありますか?

4

1 に答える 1

7

BaseクラスのGetAttributesメソッドを明示的に反映しています。

GetType()代わりにを使用するように実装を変更してください。次のように:

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