将整数值转换为枚举类型

Fra*_*anz 2 delphi

我可以确定delphi按升序将整数分配给我创建的任何枚举吗?

type
  TMyType = (mtFirst, mtSecond, mtThird); 
Run Code Online (Sandbox Code Playgroud)

肯定mtFirts总是TmyType(1)???

我试着写代码 myTypeselection := TMyType(MyRadiogroup.ItemIndex+1);

但我失败的是,整数数值在某种程度上是混合的.

Dav*_*nan 6

文件给出了答案:

默认情况下,枚举值的序数从0开始,并遵循其标识符在类型声明中列出的顺序.

因此,您认为编号从一开始的信念实际上是不正确的.情况就是这样ord(mtFirst)=0,ord(mtSecond)=1等等.

这意味着您的代码应该是:

myTypeselection := TMyType(MyRadiogroup.ItemIndex);
Run Code Online (Sandbox Code Playgroud)

因为无线电组索引也是零.

在我自己的代码中,我使用以下泛型类来执行这样的操作:

type
  TEnumeration<T> = class
  strict private
    class function TypeInfo: PTypeInfo; inline; static;
    class function TypeData: PTypeData; inline; static;
  public
    class function IsEnumeration: Boolean; static;
    class function ToOrdinal(Enum: T): Integer; inline; static;
    class function FromOrdinal(Value: Integer): T; inline; static;
    class function MinValue: Integer; inline; static;
    class function MaxValue: Integer; inline; static;
    class function InRange(Value: Integer): Boolean; inline; static;
    class function EnsureRange(Value: Integer): Integer; inline; static;
  end;

class function TEnumeration<T>.TypeInfo: PTypeInfo;
begin
  Result := System.TypeInfo(T);
end;

class function TEnumeration<T>.TypeData: PTypeData;
begin
  Result := TypInfo.GetTypeData(TypeInfo);
end;

class function TEnumeration<T>.IsEnumeration: Boolean;
begin
  Result := TypeInfo.Kind=tkEnumeration;
end;

class function TEnumeration<T>.ToOrdinal(Enum: T): Integer;
begin
  Assert(IsEnumeration);
  Assert(SizeOf(Enum)<=SizeOf(Result));
  Result := 0;
  Move(Enum, Result, SizeOf(Enum));
  Assert(InRange(Result));
end;

class function TEnumeration<T>.FromOrdinal(Value: Integer): T;
begin
  Assert(IsEnumeration);
  Assert(InRange(Value));
  Assert(SizeOf(Result)<=SizeOf(Value));
  Move(Value, Result, SizeOf(Result));
end;

class function TEnumeration<T>.MinValue: Integer;
begin
  Assert(IsEnumeration);
  Result := TypeData.MinValue;
end;

class function TEnumeration<T>.MaxValue: Integer;
begin
  Assert(IsEnumeration);
  Result := TypeData.MaxValue;
end;

class function TEnumeration<T>.InRange(Value: Integer): Boolean;
var
  ptd: PTypeData;
begin
  Assert(IsEnumeration);
  ptd := TypeData;
  Result := Math.InRange(Value, ptd.MinValue, ptd.MaxValue);
end;

class function TEnumeration<T>.EnsureRange(Value: Integer): Integer;
var
  ptd: PTypeData;
begin
  Assert(IsEnumeration);
  ptd := TypeData;
  Result := Math.EnsureRange(Value, ptd.MinValue, ptd.MaxValue);
end;
Run Code Online (Sandbox Code Playgroud)

有了这个,您的代码就会变成:

myTypeselection := TEnumeration<TMyType>.FromOrdinal(MyRadiogroup.ItemIndex);
Run Code Online (Sandbox Code Playgroud)


jpf*_*ius 6

如果没有为枚举值指定值,编译器将从零开始,因此

TMyType = (mtFirst, mtSecond, mtThird)
Run Code Online (Sandbox Code Playgroud)

相当于

TMyType = (mtFirst = 0, mtSecond = 1, mtThird = 2)
Run Code Online (Sandbox Code Playgroud)

如果使用正确的起始值0,则从整数转换为枚举并返回是安全的.