简体   繁体   中英

How to get the class from a Delphi 6 Object for assigning to a metaclass variable?

I have a Delphi 6 Metaclass variable that services a component property for a design time Server component:

type
  TClientClass = class of TClient;
...
FClientClass: class of TClientClass;
FClientObj: TClient;

I have another design-time component that is a Client component. At design time I assign a concrete instance of the Client component, dropped on to the same Form, to the Server component using the Server's "client" property via the IDE's Property Editor. However, I also want to assign the FClientClass variable the underlying class of the concrete component I am assigning to FClientObj via the "client" property. This is so the Server component can create new instances of the Client component at run time, using FClientClass.Create.

I can't figure out how to assign the underlying class of the "client" object to the FClientClass data member when I set the FClientObj data member via the Server component's property setter:

procedure setClientClass(theClient: TClient);
begin
    // Assign the "client" property.  This works.
    FClientObj := theClient;

    // Assign the class of the "client" object to the Metaclass variable.
    // THIS DOESN'T WORK: incompatible types error from the compiler.
    FClientClass := theClient;
end;

I'm pretty sure the problem is that I am trying to assign an object of TClient to a Metaclass of TClient variable. I just don't know the correct syntax to make the assignment. I don't want to just do:

FClientClass := TClient;

because I want to allow for the assignation of concrete components in the future that may be descendants of TClient.

What is the syntax for doing the assignment correctly? I'm hoping it is simpler than doing something complex with the RTTI library like as Malte's reply in this thread indicates:

How can I create an Delphi object from a class reference and ensure constructor execution?

I believe you are looking for TObject.ClassType . Use it like this:

procedure setClientClass(theClient: TClient);
begin
  FClientObj := theClient;
  FClientClass := TClientClass(theClient.ClassType);
end;

Note 1: I'm assuming that you mean FClientClass: TClientClass rather than FClientClass: class of TClientClass .

Note 2: I've only compiled this in my head; I hope it works on a real compiler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM