我有一个指向未知类实例的TObject引用。我该如何调用该未知类的构造函数以创建另一个实例?我知道Delphi具有RTTI,但不清楚如何使用。
type
TBase = class
public
constructor Create(params); virtual;
end;
TBaseClass = class of TBase;
TDerived1 = class(TBase)
public
constructor Create(params); override;
end;
TDerived2 = class(TBase)
public
constructor Create(params); override;
end;
...
var
NewObj: TBase;
begin
if SomeObj is TBase then
NewObj := TBaseClass(SomeObj.ClassType).Create(params);
end;
TComponent
工作的基本方式。一旦你有了ClassType(比如X),你就可以调用TComponentClass(X).Create(...)
。DFM流式传输通过在DFM中找到特定类名注册的ClassType并实例化它来工作。 - Disillusioned