我可以使用set类型作为数组索引吗?

Joh*_*ica 8 arrays delphi set type-safety

我不能使用set类型作为数组的大小指示器,但是对于小集合这样做是完全合理的.

假设我有以下代码:

  TFutureCoreSet = set of 0..15;
  TLookupTable = record
    FData: array[TFutureCoreSet] of TSomeRecord; //error ordinal type required
  ....
Run Code Online (Sandbox Code Playgroud)

以下代码编译和工作.

  TFutureCoreSet = set of 0..15;
  TLookupTable = record
    FData: array[word] of TSomeRecord;
Run Code Online (Sandbox Code Playgroud)

然而,这打破了允许的状态数TFutureCoreSet和查找表中的元素之间的链接.
有没有一种简单的方法来链接这两个,所以当一个更改其他更新?

Uwe*_*abe 12

只是略有不同:

type
  TFutureCore = 0..15;
  TFutureCoreSet = set of TFutureCore;
  TFutureCoreIndex = 0..(2 shl High(TFutureCore)) - 1;
  TLookupTable = record
    FData: array[TFutureCoreIndex] of TSomeRecord;
  end;
Run Code Online (Sandbox Code Playgroud)

使用a的另一个好处TFutureCoreIndex是可以使用它来强制转换TFutureCoreSet为序数类型.在对类型进行类型转换时,必须强制转换为相同大小的序数类型.

AllowedStates = LookupTable.FData[TFutureCoreIndex(FutureCores)]; //works
AllowedStates = LookupTable.FData[Integer(FutureCores)]; //invalid typecast
AllowedStates = LookupTable.FData[Word(FutureCores)]; //works, but not type safe.
Run Code Online (Sandbox Code Playgroud)