Reputation: 602
I've created an enumeration utilizing a TCustomAttribute descendant class (TEnumAttribute) to give each enumeration additional data (if successful, it will drive a custom component that can interrogate an enumeration and populate itself accordingly).
type
TShoppingCartType = (
[TEnumAttribute(0, 'All')]
sctAll,
[TEnumAttribute(1, 'Web Shopping Cart')]
sctWebShoppingCart,
[TEnumAttribute(2, 'Wish List')]
sctDefaultWebWishList,
[TEnumAttribute(3, 'Custom')]
sctWebCustomList
);
I can get the names and values just fine (using the corresponding TypeInfo GetEnum methods), but how can I access each value in the enumeration and access it's defined attribute?
Thanks for any info
Upvotes: 1
Views: 865
Reputation: 14883
As far as I can see you can only annotate types with attributes. Since a value of an enumeration is only a simple ordinal value your approach probably does not work.
If the enum values were types themselves you would use TRttiContext
and TRttiType
as described in the official docs:
http://docwiki.embarcadero.com/RADStudio/XE/en/Extracting_Attributes_at_Run_Time
Doing it the classic way seems to be more appropriate:
TShoppingCartTypeDescriptions = array[TShoppingCartType] of string;
...
Descriptions: TShoppingCartTypeDescriptions;
Descriptions[sctAll] := 'All';
Descriptions[sctWebShippingCart] := 'Web Shopping Cart';
// and so on
You can enumerate over all values using:
var
I: TShoppingCartType;
begin
for I := Low(TShoppingCartType) to High(TShoppingCartType) do
// Do something with I
end;
Upvotes: 3