我试图使用Generics将一组Bytes转换为枚举集。但是代码不编译。TValue.FromOrdinal(TypeInfo(T),Ord(B)).AsType实际上确实正确地返回枚举值,但我不能将此值包含在枚举集中。
interface 
type TByteSet = set of Byte;
type TMyNewEnum = (meZero, meOne, meTwo);
type TMyNewEnumSet = set of TMyNewEnum;
type
  TEnum<T> = class(TObject)
  public
    class function ToString(const aEnumValue: T): string; reintroduce;
    class function FromString(const aEnumString: string; const aDefault: T): T;
    class procedure FromByteSet(const Value: TByteSet; out EnumSet: TMyNewEnumSet);
  end
  implementation
Var
  MyByteSet: TMyByteSet;
  MyEnumSet: TMyNewEnumSet;
...  
class procedure TEnum<T>.FromByteSet(const Value: TByteSet; out EnumSet: TMyNewEnumSet);
var
  B: Byte;
begin
  Assert(PTypeInfo(TypeInfo(T)).Kind = tkEnumeration, 'Type parameter must be an Enumeration');
  for B in Value do
    begin
      EnumSet := EnumSet + TValue.FromOrdinal(TypeInfo(T), Ord(B)).AsType<T>; //This line does not compile
    end;
end;
...
//intended Usage
  MyByteSet := [0, 2];
  TEnum<TMyNewEnum>.FromByteSet(MyByteSet, MyEnumSet); 
  //I would like MyEnumSet to contain [meZero, meTwo]
end.有什么想法吗?
发布于 2018-11-12 18:03:40
你可以很简单地实现你想要的,但不是你想要的方式(别人已经指出了)。
如果您执行以下程序,您将在调试器中看到MyEnumSet以所需的值结束。
program Project3;
{$APPTYPE CONSOLE}
{$R *.res}
uses
  System.SysUtils;
type TByteSet = set of Byte;
type TMyNewEnum = (meZero, meOne, meTwo);
type TMyNewEnumSet = set of TMyNewEnum;
type
  TEnum<T> = class(TObject)
  public
    class procedure FromByteSet(const Value: TByteSet; out EnumSet: T);
  end;
Var
  MyByteSet: TByteSet;
  MyEnumSet: TMyNewEnumSet;
procedure Test( const Parm1 : TByteSet; out Parm2 : TMyNewEnumSet );
var
  iResult : TMyNewEnumSet absolute Parm1;
begin
  Parm2 := iResult;
end;
{ TEnum<T> }
class procedure TEnum<T>.FromByteSet(const Value: TByteSet; out EnumSet : T );
var
  iResult : T absolute Value;
begin
  EnumSet := iResult;
end;
begin
  MyByteSet := [0,2];
  TEnum<TMyNewEnumSet>.FromByteSet( MyByteSet, MyEnumSet);
end.当然,您需要添加可以使用RTTI的错误检查(界等)。
https://stackoverflow.com/questions/53266055
复制相似问题