How to cast a Interface to a Object in Delphi

前端 未结 6 1048
南旧
南旧 2020-12-01 18:39

In delphi 2009 I have a reference to a IInterface which I want to cast to the underlying TObject

Using TObject(IInterface) obv

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 19:07

    There is a nice alternative when you know the implementing object is a TComponent descendant.

    You can use the IInterfaceComponentReference interface, which is defined up in Classes unit:

    IInterfaceComponentReference = interface
      ['{E28B1858-EC86-4559-8FCD-6B4F824151ED}']
      function GetComponent: TComponent;
    end;
    

    And then it's declared in TComponent (and implemented to return self):

      TComponent = class(TPersistent, IInterface, IInterfaceComponentReference)
    

    So if you know the implementing object is a TComponent then you can do this:

    function InterfaceToComponent(const AInterface: IInterface): TComponent;
    var
      vReference: IInterfaceComponentReference;
    begin
      if Supports(AInterface, IInterfaceComponentReference, vReference) then
        result := vReference.GetComponent
      else
        result := nil;
    end;
    

提交回复
热议问题