How to save a set in a TStringList object?

I am trying to save a set inside an object property (and read it) in a TStringList (I will also use it to store the text associated with the set), but I get an invalid type for the set.

What is the best way to save a set inside a StringList? Also, should this object be freed when the StringList is destroyed?

Here is a sample code:

type
 TDummy = (dOne, dTwo, dThree);
 TDummySet = set of TDummy;


var
  DummySet: TDummySet;
  SL: TStringList;
begin
  SL := TStringList.Create;
  Try
    DummySet := [dOne, dThree];
    SL.AddObject('some string', TObject(DummySet)); // Doesn't work. Invalid typecast
  Finally
    SL.Free;
  End;
end;
+3
source share
5 answers

Read the other answers first - you might find a less hacky solution.

But FTR: you can write

SL.AddObject('some string', TObject(Byte(DummySet)));

and

DummySet := TDummySet(Byte(SL.Objects[0]));

if you really want to.

. Byte, TDummySet. , (, ), Word.

+5

.

, TDummySet . -

TExemple = class
 DummySet = TDummySet;
end;

:

:

  TDummy = (dOne, dTwo, dThree);
  TDummySet = set of TDummy;
  PDummySet = ^TDummySet;

:

var
  DummySet: PDummySet;
 begin
  New(DummySet);
  DummySet^ := [dOne, dThree];
+4

TStringList.Objects, (TObject) 32- , 256 . , .

RTTI. , VCL , JCL JclRTTI JclSetToStr JclStrToSet.

var 
  fs: TFontStyles;
begin 
  JclStrToSet(TypeInfo(TFontStyles), fs, 'fsBold, fsItalic'); // from string
  Showessage(JclSetToStr(TypeInfo(TFontStyles), fs));         // to string  
end;
+2

, - . TDummySet? , , .

var
  Test: Array of TDummySet;

SetLength(Test, 2);
Test[0] := [dOne, dThree];
Test[1] := [dTwo];

:

SetLength(Test, 0);
0

typecast TObject, .

TStringList. .

- :

type
  TEnum = (one, two, three);
  TSet = set of TEnum;
  PSet = ^TSet;
var s: TStringList;
    p: PSet;
begin
  s := TStringList.Create;
  p := AllocMem(SizeOf(TSet));
  p^ := [two, three];
  S.AddObject('a', TObject(p));

  // bla bla bla

  // Here you read the set in the string list
  if (two in PSet(S.Objects[0])^)) then begin
    // your checks here
  end

  ...
0
source

Source: https://habr.com/ru/post/1731177/


All Articles