集合和字符串的转换

 在DFW上回答了一个问题.写了些代码.为了以后用贴到这里

uses
  TypInfo;

type
  TSetDemo = set of(S1, S2, S3, S4);

procedure StrToSet(TypeInfo: PTypeInfo; const Value: string; out Result);
  function NextWord(var P: PChar): string;
  var I: Integer;
  begin
    while P^ in [',', ' ', '[', ']'] do Inc(P);
    I := 0; while P[I] in ['A'..'Z', 'a'..'z', '0'..'9', '_'] do Inc(I);
    SetString(Result, P, I); Inc(P, I);
  end;
type TMaxSet = set of Byte;
var
  ElemTypeInfo: PTypeInfo; ElemTypeData: PTypeData; P: PChar;
  EnumName: string; I, ElemValue: Integer;
begin
  ElemTypeInfo := GetTypeData(TypeInfo)^.CompType^;
  ElemTypeData := GetTypeData(ElemTypeInfo);
  for I := ElemTypeData^.MinValue to ElemTypeData^.MaxValue do Exclude(TMaxSet(Result), I);
  P := PChar(Value);
  repeat
    EnumName := NextWord(P);
    if EnumName = '' then Break;
    ElemValue := GetEnumValue(ElemTypeInfo, EnumName);
    if ElemValue < 0 then
      raise EConvertError.CreateFmt('值"%s"不正常吧!', [EnumName]);
    Include(TMaxSet(Result), ElemValue);
  until False;
end;

function SetToStr(TypeInfo: PTypeInfo; const Value; Brackets: Boolean = True): string;
type
  ByteSet = set of 0..7;
var
  ByteValue: ^ByteSet;
  I, M: Integer;
  ElemTypeInfo: PTypeInfo;
  ElemTypeData: PTypeData;
begin
  Result := '';
  ElemTypeInfo := GetTypeData(TypeInfo)^.CompType^;
  ElemTypeData := GetTypeData(ElemTypeInfo);
  ByteValue := @Value;
  for I := ElemTypeData^.MinValue to ElemTypeData^.MaxValue do
  begin
    M := I mod 8;
    if M in ByteValue^ then
    begin
      if Result <> '' then
        Result := Result + ',';
      Result := Result + GetEnumName(ElemTypeInfo, I);
    end;
    if M = 7 then Inc(ByteValue)
  end;
  if Brackets then
    Result := '[' + Result + ']';
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  S : TSetDemo;
begin
  StrToSet(TypeInfo(TSetDemo), '[S1,S3]', s);
  Edit1.Text := SetToStr(TypeInfo(TSetDemo),S, True);
end;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值