GUID(Global Unique Identifier)在Delphi中用TGUID记录结构表示:
PGUID = ^TGUID;
TGUID = packed record
D1: LongWord;
D2: Word;
D3: Word;
D4: array[0..7] of Byte;
end;
虽然SysUtils单元封装了一些常见的操作函数(CreateGUID,GUIDToString,StringToGUID,IsEqualGUID),但实际使用时总觉得不是很方便。所幸的是在Delphi 2006及以上的编译器中,支持Record Helper,所以我重新封装了一下:
type
TGuidHelper = record helper for TGUID
private
class function GetEmpty: TGUID; static;
public
{ record helper donnot support constructor }
class function Create(const g: string): TGUID; overload; static;
class function NewGuid: TGUID; static;
function Equals(const guid: TGUID): Boolean;
function ToString: string;
class property Empty: TGUID read GetEmpty;
end;
如此一来,只要引入这个单元,我们就可以用OO方式操作TGUID了:
procedure TestGuidHelper;
var
guid1, guid2: TGUID;
guidString: string;
begin
guid1 := TGUID.NewGUID;
guidString := guid1.ToString;
guid2 := TGUID.Create(guidString);
Assert(guid2.ToString = guidString);
Assert(guid1.Equals(guid2));
Assert(TGUID.Empty.ToString = '{00000000-0000-0000-0000-000000000000}');
Assert(not guid1.Equals(TGUID.Empty));
end;
下面是TGuidHelper的实现代码:
class function TGuidHelper.Create(const g: string): TGUID;
begin
Result := StringToGUID(g);
end;
class function TGuidHelper.NewGuid: TGUID;
begin
ComObj.OleCheck(SysUtils.CreateGUID(Result));
end;
class function TGuidHelper.GetEmpty: TGUID;
const
EmptyGuid: TGUID = (
D1: 0;
D2: 0;
D3: 0;
D4: (0, 0, 0, 0, 0, 0, 0, 0);
);
begin
Result := EmptyGuid;
end;
function TGuidHelper.Equals(const guid: TGUID): Boolean;
begin
Result := SysUtils.IsEqualGUID(Self, guid);
end;
function TGuidHelper.ToString: string;
begin
Result := SysUtils.GUIDToString(Self);
end;