问题描述
考虑以下示例(我使用的是Delphi XE):
Consider the following example (I am using 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.
类构造函数从不被调用,因此不会打印创建类行。
但是,如果我删除泛化,并将 TTestClass< T>
转换为标准类 TTestClass
正如预期的那样工作。
The class constructur is never called and hence the line 'class created' is not printed.However, if I remove the generalisation and make TTestClass<T>
into a standard class TTestClass
, everything works as expected.
我是用泛型缺失的东西吗?或者它根本不起作用?
Am I missing something out with generics? Or it simply doesn't work?
任何关于这一点的想法都会被呵护!
Any thoughts on this would be apprechiated!
谢谢,
--Stefan -
Thanks, --Stefan--
推荐答案
看起来像一个编译器错误。如果将TTestClass声明和实现移动到单独的单元,相同的代码可以工作。
Looks like a compiler bug. The same code works if you move the TTestClass declaration and implementation to a separate unit.
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.
这篇关于Delphi XE:类构造函数在使用泛型的类中不会被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!