4

プロパティの継承された属性をオーバーライドすることについて、細かい質問があります。

次の属性があるとします。

[AttributeUsage(AttributeTargets.All, Inherited = true)]
public class MyAttributeAttribute : Attribute

//...

public class ParentClass
{
    [MyAttribute]
    public String MyString;
}

public class ChildClass : ParentClass
{
    new public String MyString; //Doesn't have MyAttribute
}

しかしMyAttribute、 がクラスに設定されている場合はどうなるでしょうか。

[MyAttribute]
public class ParentClass

public class ChildClass; //Don't want MyAttribute

ChildClass が属性を継承しないようにする方法はありますか?


コンテキスト: 純粋に理論的です。属性を継承可能にしたいのですが、いつかそのようなことが起こった場合、それをオーバーライドできるかどうかを知りたいです。

4

1 に答える 1

3

参照する質問への回答の 1 つに記載されているBrowsableAttributeアプローチをコピーできます。ブール値を使用してコンストラクターを作成できます。これを設定するfalseと、属性は存在しますが、処理されるべきではないことを示します。プロパティを に設定するパラメーターなしのコンストラクターを追加することもできますtrue。これは、基本クラスから継承された属性をオーバーライドすることにしない限り、最も頻繁に使用するものです。

[AttributeUsage(AttributeTargets.All, Inherited = true)]
public class MyAttributeAttribute : Attribute
{
    public bool Enabled { get; private set; }

    public MyAttributeAttribute()
        :this(true)
    {
    }

    public MyAttributeAttribute(bool enabled)
    {
        Enabled = enabled;
    }
}

次に、タイプを検討して属性を探すと、Enabledプロパティを確認して、それが true の場合にのみ実際に使用できます。

クラス階層の例は次のようになります。

[MyAttribute]
public class ParentClass
[MyAttribute(false)]    
public class ChildClass; //Don't want MyAttribute
于 2012-12-10T18:53:38.043 に答える