【发布时间】:2011-03-05 08:52:40
【问题描述】:
众所周知,当我们这样调用类的构造函数时:
instance := TSomeClass.Create;
Delphi 编译器实际上做了以下事情:
- 调用静态NewInstance方法 分配内存并初始化 内存布局。
- 调用构造方法 执行类的初始化
- 调用 AfterConstruction 方法
简单易懂。但是我不太清楚编译器在第二步和第三步中是如何处理异常的。
在 D2010 中似乎没有使用 RTTI 构造方法创建实例的显式方法。所以我在Spring Framework中为Delphi写了一个简单的函数来重现创建过程。
class function TActivator.CreateInstance(instanceType: TRttiInstanceType;
constructorMethod: TRttiMethod; const arguments: array of TValue): TObject;
var
classType: TClass;
begin
TArgument.CheckNotNull(instanceType, 'instanceType');
TArgument.CheckNotNull(constructorMethod, 'constructorMethod');
classType := instanceType.MetaclassType;
Result := classType.NewInstance;
try
constructorMethod.Invoke(Result, arguments);
except
on Exception do
begin
if Result is TInterfacedObject then
begin
Dec(TInterfacedObjectHack(Result).FRefCount);
end;
Result.Free;
raise;
end;
end;
try
Result.AfterConstruction;
except
on Exception do
begin
Result.Free;
raise;
end;
end;
end;
我觉得可能不是 100% 正确。所以请给我指路。谢谢!
【问题讨论】:
标签: delphi delphi-2010 rtti