Attributes not inherited?
I played around with attributes and assumed they were inherited, but it doesn't look like this:
type
[MyAttribute]
TClass1 = class
end;
TClass2 = class(TClass1)
end;
TClass2 does not have a "MyAttribute" attribute, although it inherits from Class1. Is it possible to inherit an attribute? Or do I have to go up the class hierarchy and look for attributes?
a source to share
An attribute is a decoration for a class or other symbol, such as a method. The attribute adorns the declaration, but is not a class feature. As a result, the attribute is not inherited.
Yes, you can climb the class hierarchy to look for an attribute, but there is a better solution. Use an empty interface (IMyInterface = Interface) as the "token" interface. All descendants of a class that implements an interface will also be executors of that interface. All you need to do is make sure that your base class implements IInterface, which will already be the case if your base class derives from TInterfacedObject or TComponent.
Once you've done that, you can use the Supports function to check if this class or one of its ancestors implements the interface.
a source to share
I've never used attributes in Delphi - so this answer is kind of a guess. But I know about annotations in Java, which is basically the same thing.
But it makes sense if they are not inherited: the subclass may require different attributes, or conflict with the attributes of the superclass. Also, if attributes are not inherited, you have the option to follow the hierarchy if your "your" usecase attribute requires it. If they were inherited, it will be difficult for you to determine if the attribute is actually on a specific class and not on any of its superclasses.
If you need inheritance and don't want to look at superclasses, it might make sense to use a class function or a class property, or even a tag interface (doesn't declare any methods instead). They are inherited.
a source to share