我可以确定delphi按升序将整数分配给我创建的任何枚举吗?
type
TMyType = (mtFirst, mtSecond, mtThird);
那里肯定是mtFirts总是TmyType(1)
???
我尝试编写类似的代码 myTypeselection := TMyType(MyRadiogroup.ItemIndex+1);
但是我失败了整数值的混合。
该文档有答案:
默认情况下,枚举值的序数从0开始,并遵循其标识符在类型声明中列出的顺序。
因此,您认为编号从一开始的信念实际上是错误的。是的ord(mtFirst)=0
,ord(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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句