开发者

Attributes don't inherit?

I played with attributes and assumed that they are inherited but it doesn't seem so:

type
  [MyAttribute]
  TClass1 = class
  end;

  TClass2 = class(TClass1)
  end;

TClass2 doesn't have the Attribute "MyAttribute" although it inherits from Class1. Is there any possibility to make an attribute inheritable? Or do I have to g开发者_Python百科o up the class hierarchy and search for attributes?


An attribute is a decoration for a class or other symbol, such as a method. An attribute decorates the declaration, but is not a feature of the class. As a result, an attribute is not inherited.

Yes, you could go up the class hierarchy to look for the attribute, but there is a better solution. Use an empty interface ( IMyInterface = Interface) as a "marker" interface. All descendants of an interface-implementing class will also be implementers of that interface. All you need to ensure is that your base class implements IInterface, which will already be the case if your base class descends from TInterfacedObject or TComponent.

Once you've done this, you can use the Supports function to test if the class, or one of its ancestors, implements the interface.


I never used attributes in Delphi - so this answer is kind of speculation. But I know about annotations in Java which is basically the same thing.

But it makes sense if they are not inherited: a subclass might require other attributes, or contradict attributes from a super class. Also, if attributes are not inherited you have a chance to follow the hierarchy if "your" attribute usecase needs that. If they were inherited you would have trouble to detect whether an attribute is actually on a particular class as opposed to any of its superclasses.

If you need inheritance and don't want to look at super classes it might make more sense to use a class function, or class property, or even a tag interface (declares no methods) instead. Those are inherited.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜