相关疑难解决方法(0)

如何在Delphi 2010中使用RTTI创建对象实例?

众所周知,当我们调用类的构造函数时:

instance := TSomeClass.Create;
Run Code Online (Sandbox Code Playgroud)

Delphi编译器实际上做了以下事情:

  1. 调用静态NewInstance方法来分配内存并初始化内存布局.
  2. 调用构造函数方法来执行类的初始化
  3. 调用AfterConstruction方法

它简单易懂.但我不太确定编译器如何处理第二步和第三步中的异常.

似乎没有明确的方法在D2010中使用RTTI构造函数方法创建实例.所以我在Spring Framework for 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;
Run Code Online (Sandbox Code Playgroud)

我觉得这可能不是100%正确.所以请告诉我方式.谢谢!

delphi rtti delphi-2010

14
推荐指数
1
解决办法
3863
查看次数

标签 统计

delphi ×1

delphi-2010 ×1

rtti ×1