- Expert Delphi
- Pawe? G?owacki
- 329字
- 2021-07-02 20:44:24
Custom attributes
Custom attributes let you add custom information to a class itself or to its individual members. Many libraries that come with Delphi use custom attributes. They are useful when we want to mark certain types or type members that need to be treated in a special way. For example, in the DUnitX unit testing framework that comes with Delphi, we use the Test custom attributes to mark a method as testable and optionally provide parameters to be used by the unit test runner. Another example is the REST API resources, which are published from EMS modules. With custom attributes, we can tell the framework what should be the name of the REST resource to access a certain method.
A custom attribute is just a regular class that inherits from the TCustomAttribute type defined in a built-in system unit.
Let's consider the definition of a custom documentation attribute. A programmer could use such an attribute to associate a given class member in code with a custom URL, with more information about it. Take a look at the following code snippet:
unit uDocAttribute; interface type DocAttribute = class(TCustomAttribute) private FURL: string; public constructor Create(URL: string); property URL: string read FURL write FURL; end; implementation { DocAttribute } constructor DocAttribute.Create(URL: string); begin FURL := URL; end;
To apply an attribute, it needs to be placed just before the element it applies in square brackets. Optionally, it can take parameters that just come as a list in brackets. This will implicitly call the custom attribute constructor:
uses uDocAttribute; type [Doc('http://mydocs/MySuperClass')] // skipping "...Attribute" TMySuperClass = class public [DocAttribute('http://mydocs/MySuperClass/DoSomething')] procedure DoSomething; end;
By convention, custom attribute class names end with Attribute. Delphi compiler allows us to skip the optional Attribute part of the attribute class name.
That's nice, but how do I know in my code that there are attributes applied to classes that my code operates on? This and many other capabilities are provided by the Runtime Type Information (RTTI) system.
- PostgreSQL技術(shù)內(nèi)幕:事務(wù)處理深度探索
- Python進(jìn)階編程:編寫更高效、優(yōu)雅的Python代碼
- 零基礎(chǔ)學(xué)MQL:基于EA的自動(dòng)化交易編程
- Mastering ServiceNow(Second Edition)
- Android開發(fā)案例教程與項(xiàng)目實(shí)戰(zhàn)(在線實(shí)驗(yàn)+在線自測(cè))
- 細(xì)說Python編程:從入門到科學(xué)計(jì)算
- JavaScript動(dòng)態(tài)網(wǎng)頁編程
- Apache Camel Developer's Cookbook
- 3ds Max印象 電視欄目包裝動(dòng)畫與特效制作
- SpringBoot從零開始學(xué)(視頻教學(xué)版)
- Java EE項(xiàng)目應(yīng)用開發(fā)
- 開源網(wǎng)絡(luò)地圖可視化:基于Leaflet的在線地圖開發(fā)
- 計(jì)算機(jī)應(yīng)用基礎(chǔ)
- 3ds Max瘋狂設(shè)計(jì)學(xué)院
- Java入門經(jīng)典