嵌套泛型记录

10

当我尝试定义嵌套泛型记录时,遇到了一个奇怪的编译器错误。

嵌套在类和接口中是有效的,但是在记录中却不行。

type
  TRec<T> = record
    Value: T;
  end;

  TCls = class
  public
    Rec: TRec<TRec<Integer>>;
  end;

这段代码在Delphi Berlin 10.1.2和Tokyo 10.2.3上都无法编译。是语言本身的限制还是编译器的问题呢?

错误信息如下:

[dcc32 Error] Project1.dpr(22): E2564 Undefined type 'TRec<T>'

我只是想嵌套使用Spring.Nullable<>类型,但不起作用。之后我用一个简单的泛型记录快速重现了这个问题。


@LURD:不行。同样的错误。 - Z.B.
嗯,在我的 Delphi 10.2 Tokyo update 2 中至少可以编译。 - LU RD
2
@LURD,这段代码在所有Delphi版本中都可以编译通过。我很确定提问者没有编译你的代码,并且误读了你的评论。我也独立发现了同样的解决方法。 - David Heffernan
@DavidHeffernan: 程序 Project1;{$APPTYPE CONSOLE}{$R *.res}type TCls = class private type Trec1<T1> = record Value : T1; end; public Rec: TRec<TRec1<Integer>>; end;begin end. 错误:[dcc32 错误] Project84.dpr(8):未声明的标识符:“TRec<>” - Z.B.
在 Berlin 10.1 更新2中。24.0.25048.9432。 - Z.B.
显示剩余6条评论
1个回答

9
这是一个编译器错误,您应该提交错误报告。考虑以下内容:
type
  TRec<T> = record
    Value: T;
  end;

var
  Rec: TRec<TRec<Integer>>; // compiles successfully
  RecArray: TArray<TRec<TRec<Integer>>>; // compiles successfully

procedure foo;
var
  Rec: TRec<TRec<Integer>>; // compiles successfully
begin
end;

type
  TContainingClass = class
    Rec: TRec<TRec<Integer>>; // E2564 Undefined type 'TRec<T>'
  end;

  TContainingRecord = record
    Rec: TRec<TRec<Integer>>; // E2564 Undefined type 'TRec<T>'
  end;

  TContainingObject = object
    Rec: TRec<TRec<Integer>>; // E2564 Undefined type 'TRec<T>'
  end;

缺陷似乎是在使用类型时出现在聚合复合类型内。
虽然这有点不好,但这是我能找到的唯一解决方法:
type
  TRec<T> = record
    Value: T;
  end;

  TRecRec<T> = record
    Value: TRec<T>;
  end;

  TContainingClass = class
    Rec: TRecRec<Integer>;
  end;

但在任何实际应用场景中,这都没有什么用处。

希望 Idera 能够解决这个问题。否则,每次想要嵌套一个单独的记录类型时,这可能是一个令人讨厌的限制。感谢您的时间,David。 - Z.B.
Idera不会修复它,但Embarcadero也许会。它仍然是Embarcadero Delphi。 - Rudy Velthuis
现在无法检查,但是如果您在类/记录/对象声明中有Unit1.TRec<Unit1.TRec<Integer>>作为类型(假设Unit1是定义TRec的单元名称),会怎样呢? - Rudy Velthuis
@RudyVelthuis E2564 未定义类型 'TRec<T>'。 - David Heffernan
1
@Z.B. 如果问题没有被报告,他们就不会修复它 - 请你或者让我知道,然后我来报告。 - Stefan Glienke
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接