Search code examples
delphidelphi-xe2

Attribute constructor with array parameter


well today i was re-writing some olds stuff here and got myself into a problem that i don't know the answer.

i created the following attribute:

Enumeration<T> = class(TCustomAttribute)
strict private
    { Private declarations }
    FValues : TList<T>;
public
    { Public declarations }
    constructor Create(const AValues : array of T);
    destructor Destroy(); override;
public
    { Public declarations }
    property Values : TList<T> read FValues;
end;

with that in mind, i can use this attribute just fine in the following class for example:

[Entity('tablename')]
TUser = class(TEntity)
strict private
   [Column('idcolumnname')]
   [PrimaryKey(True)]
   Fid : TInteger;

   [Column('typecolumnname')]
   [Enumeration<string>(['A', 'B', 'C', 'D', '...'])]
   Ftype: TEnumeration<string>;
end;

it is great that it worked but idk, it seems to me that this should'nt work, couse in my ignorance, delphi attributes expect only constant types and im not only using array as a paremeter but a generic one.

moving foward, i made this attribute:

Association = class(TCustomAttribute)
strict private
    { Private declarations }
    FMasterKeys : TList<string>;
    FDetailKeys : TList<string>;
public
    { Public declarations }
    constructor Create(const AMasterKeys, ADetailKeys : array of string);
    destructor Destroy(); override;
public
    { Public declarations }
    property MasterKeys : TList<string> read FMasterKeys;
    property DetailKeys : TList<string> read FDetailKeys;
end;

and tried to use on this class:

[Entity('tablename')]
TSuperUser = class(TEntity)
strict private
    [Association(['masterkey'], ['detailkey'])]
    Fuser : TAssociation<TUser>;
end;

i got a error [DCC Error] E2026 Constant expression expected.

ok, so in resume i just dont know whats happening why i can use a array of T as a attribute parameter and not a array of string for instance.

thx for any help in advance


Solution

  • Check your compiler warnings. It should say W1025 Unsupported language feature: 'custom attribute' for your "compiling code". So what you though compiles did in fact not. It just did not raise an error.

    This is usually the case when an attribute class cannot be found because fact you cannot have generic attributes. And is still the case in XE7.

    Bottom line: Even if it did compile your executable will not contain that attribute.