Einzelnen Beitrag anzeigen

Benutzerbild von s.h.a.r.k
s.h.a.r.k

Registriert seit: 26. Mai 2004
3.159 Beiträge
 
#9

AW: Generisches ToString für Enumerations

  Alt 30. Apr 2011, 16:17
Ich unterstütze alles ab Delphi 2010, da ich teilweise rege Verwendung der neuen RTTI mache. Nachdem es auch die netten Generics gibt, will ich dem Nutzer der Log-Komponente (Hauptnutzer bin wohl ich ) so viel wie möglich abnehmen. Daher mein Ansatz, aber danke für den Hinweis.

-- Edit: Hier noch schnell der Record mit den entsprechenden Methoden. Die Methode StrToEnum() gibt es in der TypInfo-Unit auch und heißt dort GetEnumValue(). Allerdings liefert GetEnumValue() einen Integer und müsste somit nochmals zusätzlich gecastet werden, was hier nicht der Fall ist -> Typsicherheit!
Delphi-Quellcode:
TEnumHelper = record
  class function EnumToStr<T>(Value: T): String; static;
  class function StrToEnum<T>(Value: String): T; static;
end;

class function TEnumHelper.EnumToStr<T>(Value: T): String;
var
  ti : PTypeInfo;
begin
  ti := TypeInfo(T);
  if (ti = nil) then
    raise Exception.Create('Type has not type information.');
  if (ti.Kind <> tkEnumeration) then
    raise Exception.Create('Type is not an enumeration.');
  Result := GetEnumName(ti, PByte(@Value)^);
end;

class function TEnumHelper.StrToEnum<T>(Value: String): T;
var
  ti : PTypeInfo;
  i : Byte;
  pt : ^T;
begin
  ti := TypeInfo(T);
  if (ti = nil) then
    raise Exception.Create('Type has not type information.');
  if (ti.Kind <> tkEnumeration) then
    raise Exception.Create('Type is not an enumeration.');

  i := GetEnumValue(ti, Value);
  pt := @i;
  Result := pt^;
end;
Wenn noch wer was dran auszusetzen hat, dann nur her damit
»Remember, the future maintainer is the person you should be writing code for, not the compiler.« (Nick Hodges)

Geändert von s.h.a.r.k (30. Apr 2011 um 16:33 Uhr)
  Mit Zitat antworten Zitat