views:

60

answers:

1

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

+3  A: 

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 themselfes 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;
Jens Mühlenhoff
@Jens, thanks! I've probably spend the last 6 hours playing with every permutation of getting the correct value(s). I was hoping for a 'Marco Cantu'-ish slight-of-hand trick that's not documented. :)
KevinRF
@KevinRF: No problem, sometimes it is the easy solutions that work best. As an alternative you could also use a dictionary or other smart data structure to solve your problem.
Jens Mühlenhoff