Do Delphi attributes require a constant parameter? If so, why?

Consider the following (incompatible) code:

program AttributesTestProgram; {$APPTYPE CONSOLE} uses SysUtils, Classes, RTTI; type TDisplayTextAttribute = class(TCustomAttribute) private FDisplayText: string; public constructor Create(aDisplayText: string); property DisplayText: string read FDisplayText write FDisplayText; end; constructor TDisplayTextAttribute.Create(aDisplayText: string); begin FDisplayText := aDisplayText; end; function GetFirstName: string; begin Result := 'First Name'; end; type TCustomer = Class(TObject) private FFirstName: string; FLastName: string; FStreetAddress: string; FZIP: string; FState: string; FCity: string; FPhone: string; published [TDisplayTextAttribute(GetFirstName)] property FirstName: string read FFirstName write FFirstName; end; begin // Code that does the work removed for clarity.... Readln; end. 

I wonder why this fails to compile with an error:

 [DCC Error] AttributesTestProgram.dpr(40): E2026 Constant expression expected 

I suppose it has something to do with the idea that attributes should be bound at compiler time or something in that direction.

Therefore, my questions are as follows:

Is there a way to “beat the system” here and get the runtime value at that location in the attribute?

+6
source share
1 answer

Yes, you need constants, because parameters are evaluated into constants at compile time and stored in RTTI tables. In addition, attributes refer to a class, not to objects, so if you have more than one TCustomer, your idea becomes meaningless.

You can beat the system by giving the attribute a constructor without parameters (or no constructor at all) and changing the DisplayText property to a method on it that accepts either a string or an object from which you can extract a string.

+8
source

Source: https://habr.com/ru/post/887743/


All Articles