10

以下のコードでカスタム .NET 属性を作成しようとしましたが、誤ってサブクラスを省略してしまいました。これにより、コメントに示されている簡単に修正できるコンパイラ エラーが生成されました。

// results in compiler error CS0641: Attribute 'AttributeUsage' is 
// only valid on classes derived from System.Attribute
[AttributeUsage(AttributeTargets.Class)]
internal class ToolDeclarationAttribute
{
    internal ToolDeclarationAttribute()
    {
    }
}

[AttributeUsage]私の質問は、属性がのサブクラスにのみ適用できることをコンパイラーがどのように知っているSystem.Attributeかです。AttributeUsageAttribute.NET Reflector を使用しても、クラス宣言自体に特別なことは何もありません。残念ながら、これはコンパイラ自体によって生成された特殊なケースにすぎない可能性があります。

[Serializable, ComVisible(true), AttributeUsage(AttributeTargets.Class, Inherited=true)]
public sealed class AttributeUsageAttribute : Attribute
{
    ...

カスタム属性を特定のクラス (またはインターフェイス) のサブクラスにのみ配置できるように指定できるようにしたいと考えています。これは可能ですか?

4

3 に答える 3

27

カスタム属性を特定のクラス(またはインターフェイス)のサブクラスにのみ配置できるように指定できるようにしたいと思います。これは可能ですか?

実際には、サブクラス(インターフェイスではない)に対してこれを行う方法があります-属性の使用の制限protectedを参照してください。コードを再現するには(ただし、ディスカッションは再現しません):

abstract class MyBase {
    [AttributeUsage(AttributeTargets.Property)]
    protected sealed class SpecialAttribute : Attribute {}
}
class ShouldBeValid : MyBase {
    [Special] // works fine
    public int Foo { get; set; }
}
class ShouldBeInvalid { // not a subclass of MyBase
    [Special] // type or namespace not found
    [MyBase.Special] // inaccessible due to protection level
    public int Bar{ get; set; }
}
于 2009-07-27T21:32:28.053 に答える
2

AttributeUsageAttribute単なる魔法のクラスです(Attributeそれ自体がそうであるように)。これは組み込みのコンパイラルールであり、独自の属性に対してそのようなことを行うことはできません。

于 2009-07-27T21:17:44.887 に答える
0

ReSharper を使用すると、[JetBrains.Annotations.BaseTypeRequired(typeof(YouBaseType))]

于 2016-11-29T16:53:16.410 に答える