Delphi XE:类构造函数不会在使用泛型的类中调用



考虑以下示例(我使用的是Delphi XE):

program Test;
{$APPTYPE CONSOLE}
type
  TTestClass<T> = class
  private
    class constructor CreateClass();
  public
    constructor Create();
  end;
class constructor TTestClass<T>.CreateClass();
begin
  // class constructor is not called. this line never gets executed!
  Writeln('class created');
end;
constructor TTestClass<T>.Create();
begin
  // this line, of course, is printed
  Writeln('instance created');
end;
var
  test: TTestClass<Integer>;
begin
  test := TTestClass<Integer>.Create();
  test.Free();
end.

从未调用类constructur,因此不会打印行"class created"。然而,如果我去掉泛化,将TTestClass<T>变成标准类TTestClass,那么一切都会按预期进行。

我是不是错过了仿制药?或者根本不起作用?

对此有任何想法都会受到赞赏!

谢谢,--Stefan--

我可以确认这是一个错误。如果类的唯一实例化在.dpr文件中,则类构造函数不会运行。如果您创建另一个单元,即一个单独的.pas文件,并从中实例化一个TTestClass<Integer>,那么您的类构造函数将运行。

我已提交QC#103798。

看起来像是一个编译器错误。如果将TTestClass声明和实现移到一个单独的单元中,同样的代码也会起作用。

unit TestClass;
interface
type
  TTestClass<T> = class
  private
    class constructor CreateClass();
  public
    constructor Create();
  end;
var
  test: TTestClass<Integer>;
implementation
class constructor TTestClass<T>.CreateClass();
begin
  Writeln('class created');
end;
constructor TTestClass<T>.Create();
begin
  Writeln('instance created');
end;
end.

最新更新