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
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.