Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi 2010 RTTI : Explore Enumerations

Considering such an enumeration :

type
  TTypeOfData = (
    [XmlName('ABC')] todABC,
    [XmlName('DEF')] todDEF,  
    [XmlName('GHI')] todGHI
  );

Where XmlName is a custom attribute used to define the serialization string for members of this enumeration.

How can I explore the attributes attached to each member of this enumeration ?

like image 808
ZeDalaye Avatar asked Jan 25 '10 17:01

ZeDalaye


3 Answers

While Barry clearly answered your question regarding the attributes on enum elements, I'll take a stab at another suggestion. From your example, you're prefixing each enum element with 'tod' as is traditional in Delphi because enum elements are global in scope (ie. if you had an identifier todABC in scope in addition to the todABC enum elements, you could get some odd behaviors).

Starting in D2007, we introduced the notion of "scoped enums" which, when enabled, require you to qualify the enum element with the identifier of the enum itself. For instance:

{$SCOPEDENUMS ON}
type
  TTypeOfData = (ABC,DEF,GHI);

Will require you to refer to the ABC element as TTypeOfData.ABC. This allows you to use non-prefixed enum element identifiers and not run the risk of having conflicts since the elements are "scoped" to the enumeration. Any enum declared while {$SCOPEDENUMS} is enabled will behave in this manner.

Given that, you can now safely use the RTTI to get the actual enum element names in the format you wish.

like image 172
Allen Bauer Avatar answered Sep 21 '22 13:09

Allen Bauer


Attributes associated with elements in enumerations are not currently stored in Win32 RTTI data in the executable. RTTI is already responsible for a fair increase in the size of executables, so some lines had to be drawn somewhere. Attributes in Delphi Win32 are supported on types, on fields of records, and fields, methods, their parameters, and properties of classes.

The attribute declarations don't cause errors because of backward compatibility with Delphi for .NET.

like image 14
Barry Kelly Avatar answered Sep 21 '22 13:09

Barry Kelly


These is a good overview of RTTI in Delphi 2010 on the web: http://robstechcorner.blogspot.com/2009/09/so-what-is-rtti-rtti-is-acronym-for-run.html

You can get the enumeration values and back the ordinals using the "OLD" RTTI functions in the unit TypInfo (GetEnumValue, GetEnumName). And clip off the lowercase letters you get the same result as above but it is not as flexible.

like image 3
Ritsaert Hornstra Avatar answered Sep 19 '22 13:09

Ritsaert Hornstra