Using Generic Enumerations

I am trying to create a general class to which I can use a set of enumerations to initialize the values ​​inside. For instance:

constructor TManager<TEnum>.Create;
var
  enum: TEnum;
  enumObj: TMyObject;
begin
  fMyObjectList:=  TObjectDictionary<TEnum,TMyObject>.Create([doOwnsValues],10);
  for enum:= Low(TEnum) to High(TEnum) do
  begin
    enumObj:= TMyObject.Create();
    fMyObjectList.Add(enum, enumObj);
  end;
end;

In addition, later methods will retrieve objects through an enumeration value, for example:

function TManager<TEnum>.Fetch(enum: TEnum): TMyObject;
begin
  fMyObjectList.TryGetValue(enum, Result);
end;

However, passing as a generic parameter, delphi does not know what TEnum will list. Can I apply this somehow?

+5
source share
2 answers

As David said, the best you can do is run-time with RTTI.

    type  
      TRttiHelp = record
        class procedure EnumIter<TEnum {:enum}>; static;
      end;

    class procedure TRttiHelp.EnumIter<TEnum {:enum}>;
    var
      typeInf: PTypeInfo;
      typeData: PTypeData;
      iterValue: Integer;
    begin
      typeInf := PTypeInfo(TypeInfo(TEnum));
      if typeInf^.Kind <> tkEnumeration then
        raise EInvalidCast.CreateRes(@SInvalidCast);

      typeData := GetTypeData(typeInf);
      for iterValue := typeData.MinValue to typeData.MaxValue do
        WhateverYouWish;
    end;  

Although I don’t know how the code works when your listing has certain meanings, such as

    (a=9, b=19, c=25)

Edit:

iterValue , , enum helper class by Jim Ferguson

class function TRttiHelp.EnumValue<TEnum {:enum}>(const aValue: Integer): TEnum;
var
  typeInf: PTypeInfo;
begin
  typeInf := PTypeInfo(TypeInfo(TEnum));
  if typeInf^.Kind <> tkEnumeration then
    raise EInvalidCast.CreateRes(@SInvalidCast);

  case GetTypeData(typeInf)^.OrdType of
    otUByte, otSByte:
      PByte(@Result)^ := aValue;
    otUWord, otSWord:
      PWord(@Result)^ := aValue;
    otULong, otSLong:
      PInteger(@Result)^ := aValue;
  else
    raise EInvalidCast.CreateRes(@SInvalidCast);
  end;
end;

.

+5

, low() high() . , .

, . , RTTI, ( Tobias).


, , TObjectDictionary<TEnum,TMyObject>. , TMyObject TEnum. TObjectDictionary, TDictionary, TMyObject. -, , , TObjectDictionary .

. @RRUZ : Generics.Collections.TObjectDictionary

+2

All Articles