【发布时间】:2016-12-06 00:20:16
【问题描述】:
有没有办法从父类调用子类的创建?下面是这个 Duplicate 方法,我希望在其中调用子类的构造函数,以便底部的测试成功。
type
IBla<T> = interface(IInvokable)
['{34E812BF-D021-422A-A051-A492F25534C4}']
function GetIntFromIface(): Integer;
function Duplicate(): IBla<T>;
end;
TClassA<T> = class(TInterfacedObject, IBla<T>)
protected
function GetInt(): Integer; virtual;
public
function GetIntFromIface(): Integer;
function Duplicate(): IBla<T>;
end;
TClassB = class(TClassA<Integer>, IBla<Integer>)
protected
function GetInt(): Integer; override;
end;
function TClassA<T>.Duplicate: IBla<T>;
begin
Exit(TClassA<T>.Create());
end;
function TClassA<T>.GetInt: Integer;
begin
Exit(1);
end;
function TClassA<T>.GetIntFromIface: Integer;
begin
Exit(GetInt());
end;
function TClassB.GetInt: Integer;
begin
Exit(2);
end;
procedure TestRandomStuff.Test123;
var
o1, o2: IBla<Integer>;
begin
o1 := TClassB.Create();
o2 := o1.Duplicate();
Assert.AreEqual(o2.GetIntFromIface, 2);
end;
【问题讨论】:
-
有什么特别的理由想要这个泛型?无论你想要实现什么,我都觉得有点复杂。您确定要将代码简化为您要解决的问题吗?
-
我正在尝试简化现有代码,因此必须在现有代码、时间限制和我的 Delphi 技能的范围内工作。
-
我不确定这对泛型有多大影响,我无法对其进行测试:为
TClassA<T>声明一个虚拟构造函数。然后在TClassA<T>.Duplicate调用Result := TClassA<T>(Self.ClassType).Create(); -
抱歉,您不需要虚拟构造函数。您需要
type TClassAType = class of TClassA<T>;并使用以下命令创建对象:Result := TClassAType(Self.ClassType).Create; -
我尝试了类引用,但就我的发现而言,它们不适用于泛型类型(即不编译)。