使用GetEnumName和GetEnumValue获取枚举类型的名称和数值
在窗体上添加两个按钮,简单代码如下。GetEnumValue()超范围时返回-1.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,TypInfo;
type
TTestEnum=(teOne,teTwo,teThree);
TForm1 = class(TForm)
btn1: TButton;
btn2: TButton;
procedure btn1Click(Sender: TObject);
procedure btn2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btn1Click(Sender: TObject);
var
pt: PTypeInfo;
begin
pt:=TypeInfo(TTestEnum);
Caption:=GetEnumName(pt,Ord(teTwo));
end;
procedure TForm1.btn2Click(Sender: TObject);
var
pt: PTypeInfo;
begin
pt:=TypeInfo(TTestEnum);
Caption:=IntToStr(GetEnumValue(pt,'teTwo'));
end;
end.