集合和字符串的转换

转自我的旧博客

?在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;

此条目发表在Delphi, 未分类分类目录。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

你必须启用JavaScript