gpt4 book ai didi

delphi - 将整数值转换为枚举类型

转载 作者:行者123 更新时间:2023-12-01 18:58:23 33 4
gpt4 key购买 nike

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

type
TMyType = (mtFirst, mtSecond, mtThird);

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

我尝试编写类似 myTypeselection := TMyType(MyRadiogroup.ItemIndex+1); 的代码

但我认为整数值以某种方式混合。

最佳答案

documentation有答案:

By default, the ordinalities of enumerated values start from 0 and follow the sequence in which their identifiers are listed in the type declaration.

因此,您认为编号从 1 开始的观点实际上是错误的。 ord(mtFirst)=0ord(mtSecond)=1 等情况就是如此。

这意味着您的代码应为:

myTypeselection := TMyType(MyRadiogroup.ItemIndex);

因为单选组索引也是从零开始的。

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

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;

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

myTypeselection := TEnumeration<TMyType>.FromOrdinal(MyRadiogroup.ItemIndex);

关于delphi - 将整数值转换为枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21399427/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com