首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > .NET >

请问:枚举类型与数字能否互相转换

2012-09-24 
请教:枚举类型与数字能否互相转换?TCommandType (ctEmptyCommand,ctAdd,ctModify)能否根据枚举类型的值

请教:枚举类型与数字能否互相转换?
TCommandType = (ctEmptyCommand,ctAdd,ctModify);
能否根据枚举类型的值得到数字,比如如果为ctAdd,则返回一个数字1(也可能是2),
如果数字1,得到的枚举类型为ctAdd
请问大家有什么方法可以做到吗?

[解决办法]
可以,不过要对应,比如 ctEmptyCommand是0,后面加一,如果 ctEmptyCommand=2,那么 ctEmptyCommand对应的是2,后面依次加一
[解决办法]
可以,不过要对应,比如 ctEmptyCommand是0,后面加一,如果 ctEmptyCommand=2,那么 ctEmptyCommand对应的是2,后面依次加一
[解决办法]
默认是从0开始的,后面递增,即等价于下面这样:
TCommandType = (ctEmptyCommand=0,ctAdd,ctModify);

也可以改成
TCommandType = (ctEmptyCommand=3,ctAdd,ctModify);

取序数用Ord
第1种Ord(ctAdd),结果是1
第2种Ord(ctAdd),结果是4

[解决办法]
先定义常量
const
Const_enum1 = 1;
Const_enum2 = 2;
........
Const_enum15 = 15;

然后定义枚举:
如果是顺序的:
type
TMyEnum = (me01 = Const_enum1,...,me15);
如果不是顺序的:
TMyEnum = (me01 = Const_enum1,me02=Const_enum2...,me15=Const_enum15);

然后就是Ord(me01)=Const_enum1;TMyEnum(Const_enum1)=me01;



[解决办法]
强制类型转换即可。

[解决办法]

Delphi(Pascal) code
unit Unit1;interfaceuses  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  Dialogs, StdCtrls, TypInfo ;type  TForm1 = class(TForm)    Button1: TButton;    procedure Button1Click(Sender: TObject);  private    { Private declarations }  public    { Public declarations }  end;type  TCommandType = (ctEmptyCommand, ctAdd, ctModify);  TCommandTypeConvert=class  public    class function CommandToString(ACommand: TCommandType): string;    class function StringToCommand(const AStrCommand: string): TCommandType;  end;var  Form1: TForm1;implementation{$R *.dfm}class function TCommandTypeConvert.CommandToString(  ACommand: TCommandType): string;begin  Result := GetEnumName(TypeInfo(TCommandType),Ord(ACommand));end;class function TCommandTypeConvert.StringToCommand(  const AStrCommand: string): TCommandType;begin  Result := TCommandType(GetEnumValue(TypeInfo(TCommandType), AStrCommand));end;procedure TForm1.Button1Click(Sender: TObject);//函数应用:var v: TCommandType;begin  v:=ctAdd;  //枚举类型的值得到数字:  showmessage(inttostr(ord(v)));  //数字得到枚举类型值的名:  showmessage(TCommandTypeConvert.CommandToString(TCommandType(1)));end;end.
[解决办法]
来个更直接的:
Delphi(Pascal) code
unit Unit1;interfaceuses  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  Dialogs, StdCtrls ;type  TForm1 = class(TForm)    Button1: TButton;    procedure Button1Click(Sender: TObject);  private    { Private declarations }  public    { Public declarations }  end;type  TCommandType = (ctEmptyCommand,ctAdd,ctModify);var  Form1: TForm1;implementationuses TypInfo;{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);//函数应用:var v: TCommandType;    v_int:integer;begin  v:=ctAdd;  v_int:=2;  //枚举类型的值得到数字:  showmessage(inttostr(ord(v)));  //数字得到枚举类型值的名:  showmessage( GetEnumName(TypeInfo(TCommandType),v_int));end;end. 

热点排行