Specify required base class for .NET attribute targets

后端 未结 3 419
孤独总比滥情好
孤独总比滥情好 2020-12-10 04:54

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.

相关标签:
3条回答
  • 2020-12-10 05:29

    With ReSharper you can use [JetBrains.Annotations.BaseTypeRequired(typeof(YouBaseType))]

    0 讨论(0)
  • 2020-12-10 05:31

    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; }
    }
    
    0 讨论(0)
  • 2020-12-10 05:47

    AttributeUsageAttribute is just a magic class (like Attribute itself is). This is a built-in compiler rule, and you cannot do something like that for your own attributes.

    0 讨论(0)
提交回复
热议问题