枚举和字符串互转

来源:互联网 发布:java 短信防刷 编辑:程序博客网 时间:2024/06/05 09:01
{ And you want in run-time to get a string with same value for each of them  (for example, fill the Listbox items with enum values), then you can use the next procedure: }unit Unit1;interfaceuses TypInfo, Winapi.Windows, Winapi.Messages, System.SysUtils;type  TMyEnum = (One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten);  TMySet = set of TMyEnum;  TTest = (test1, test2, test3);  TTests = set of TTest;implementation//枚举转字符串数组procedure EnumToArs;var  i: Integer;  Ars: Array of String;begin  for i := Ord(Low(TMyEnum)) to Ord(High(TMyEnum)) do  begin    SetLength(Ars, Length(Ars) + 1);    Ars[high(Ars)] := (GetEnumName(TypeInfo(TMyEnum), i));  end;end;//字符串转枚举值function StrToEnum(const Value: String): TMyEnum;begin  result := TMyEnum(GetEnumValue(TypeInfo(TMyEnum), Value));end;function EnumToStr(const Value: TMyEnum): String;begin  result := GetEnumName(TypeInfo(TMyEnum), Ord(Value));end;function GetSetString(P: PTypeInfo; const Value): string;var  i: Integer;  BaseType: PTypeInfo;begin  result := '';  BaseType := GetTypeData(P)^.CompType^;  for i := 0 to High(Byte) - 1 do    if i in TIntegerSet(Value) then      result := result + GetEnumName(BaseType, i) + ',';  if result <> '' then    Delete(result, Length(result), 2);  result := Format('[%s]', [result]);end;procedure GetSetValue(SetType: PTypeInfo; const Value: string; var result);var  P, S: PChar;  Len: Integer;  EnumName: string;  EnumType: PTypeInfo;  procedure IncludeResult;  begin    Len := P - S;    SetLength(EnumName, Len);    Move(S^, EnumName[1], Len);    EnumName := Trim(EnumName);    Include(TIntegerSet(result), GetEnumValue(EnumType, EnumName));  end;begin  TIntegerSet(result) := [];  EnumType := GetTypeData(SetType)^.CompType^;  P := PChar(Value);  S := P;  while True do    case P^ of      '[':        begin          Inc(P);          S := P;        end;      ',':        begin          IncludeResult;          Inc(P);          S := P;        end;      #0, ']':        begin          IncludeResult;          break;        end;    else      Inc(P);    end;end;function M1: String;begin  result := GetSetString(TypeInfo(TTests), [test1, test2]);end;function M2: String;var  V: TTests;begin  GetSetValue(TypeInfo(TTests), '[test1, test2, test3]', V);  if test1 in V then    result := 'test1 in V';  if test2 in V then    result := ('test2 in V');  if test3 in V then    result := ('test3 in V');end;end.

0 0
原创粉丝点击