How to create an instance of object with RTTI in Delphi 2010?

后端 未结 1 1980
小蘑菇
小蘑菇 2020-12-28 09:45

As we all known, when we call a constructor of a class like this:

instance := TSomeClass.Create;

The Delphi compiler actually do the follow

相关标签:
1条回答
  • 2020-12-28 09:56

    Invoking the constructor and passing the class as the Self argument (as opposed to an instance) will correctly construct the class. The process of constructing includes the NewInstance, AfterConstruction etc. that you are manually doing here: it's not necessary.

    This ought to be sufficient:

    Result := constructorMethod.Invoke(instanceType.MetaclassType, arguments);
    

    An oddity of Delphi is how it permits constructors to be called on instances as well as classes. This feature is used as a kind of "placement new" (in C++ terminology) for form construction, so that the global form variable (e.g. Form1 by default for the first form) is assigned at the time that the OnCreate constructor gets invoked. Thus, your code doesn't raise an exception. But it is more normal to pass the class rather than the instance as the Self argument.

    0 讨论(0)
提交回复
热议问题