Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I tried to create a custom .NET attribute with the code below but accidentally left off the subclass. This generated an easily-fixed compiler error shown in the comment.

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

My question is how does the compiler know the [AttributeUsage] attribute can only be applied to a subclass of System.Attribute? Using .NET Reflector I don't see anything special on the AttributeUsageAttribute class declaration itself. Unfortunately this might just be a special case generated by the compiler itself.

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

I would like to be able to specify that my custom attribute can only be placed on subclasses of a particular class (or interface). Is this possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
491 views
Welcome To Ask or Share your Answers For Others

1 Answer

I would like to be able to specify that my custom attribute can only be placed on subclasses of a particular class (or interface). Is this possible?

Actually, there is a way to do this for subclasses (but not interfaces) using protected - see Restricting Attribute Usage. To reproduce the code (but not the discussion):

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...