How to save/load Set of Types?

后端 未结 9 1333
傲寒
傲寒 2020-12-06 00:47

I have this code

type
  TXSample = (xsType1, xsType2, xsType3, xsType4, xsType5, xsType6, xsType6, xsTyp7, xsType8); // up to FXSample30;  
..

private
  FX         


        
9条回答
  •  臣服心动
    2020-12-06 01:20

    Personally, I would convert the set to an integer and store it in the database as an INT field, like others suggested. @teran suggested using the TIntegerSet type, and here is my approach working on native integers using bit operations.

    Note that you can use SampleInInteger() to determine whether a certain element from the enumeration is present in the integer mask generated by SampleSetToInteger().

    Here's the code:

    program Project1;
    
    {$APPTYPE CONSOLE}
    
    {$R *.res}
    
    uses
      System.SysUtils;
    
    type
      { .: TXSample :. }
      TXSample = (xsType1 = 0, xsType2, xsType3, xsType4, xsType5,
        xsType6, xsType7, xsType8); // up to FXSample30;
      TXSampleSet = set of TXSample;
    
    // Converts a TXSampleSet to an integer.
    function SampleSetToInteger(const S: TXSampleSet): Integer;
    var
      Sample: TXSample;
    begin
      Result := 0;
    
      for Sample := Low(TXSample) to High(TXSample) do
        if (Sample in S) then
          Result := Result or (1 shl Ord(Sample));
    end;
    
    // Converts an integer to TXSampleSet.
    function IntegerToSampleSet(const Int: Integer): TXSampleSet;
    var
      I: Integer;
    begin
      Result := [];
    
      for I := 0 to Ord(High(TXSample)) do
        if Int and (1 shl I) <> 0 then
          Result := Result + [TXSample(I)];
    end;
    
    // Checks if a TXSample is present in the integer.
    function SampleInInteger(const S: TXSample; const Int: Integer): Boolean;
    begin
      Result := Int and (1 shl Ord(S)) <> 0;
    end;
    
    var
      XSample, XSample1: TXSampleSet;
      Tmp: Integer;
    begin
      XSample := [xsType2, xsType4, xsType5, xsType6, xsType7];
      XSample1 := [xsType1];
      Tmp := SampleSetToInteger(XSample);
    
      Writeln(Tmp);
      XSample1 := IntegerToSampleSet(Tmp);
      if (xsType5 in XSample1) then
        Writeln('Exists');
      if (SampleInInteger(xsType1, Tmp)) then
        Writeln('Exists in int');
    
    
      Readln;
    end.
    

提交回复
热议问题