Restrict custom attribute so that it can be applied only to Specific types in C#?

前端 未结 2 1508
忘了有多久
忘了有多久 2020-12-10 04:20

I have a custom attribute which is applied to class properties and the class itself. Now all the classes that must apply my custom attribute are derived from a single base c

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-10 04:35

    I'm not aware of any way to do this with custom attributes.
    A better way would be to get the classes to implement an interface with a generic constraint

    so

    class MyAttribute
    {
         // put whatever custom data you want in here
    }
    
    interface IAttributeService where T : MyBaseClass
    {
         MyAttribute Value{get;}
    }
    

    then your base class would do this

    class MyBaseClass : IAttributeService
    {
         private MyAttribute m_attrib;
    
         IAttributeService.Value
         {
             get {return m_attrib;}
         }
    }
    

    That way the compiler will enforce the constraint at compile time so that only classes
    derived from MyBaseClass can implement the interface.
    I made it fairly extensible by defining a MyAttribute class but you could of course just return a string or a bool if you needed something simpler

    I also made the MyAttribute member private so that derived classes couldn't see it and change it but could make it protected and allow derived classes access if you wanted to.

提交回复
热议问题