【问题标题】:How to get an interface from an object created from a TClass?如何从 TClass 创建的对象中获取接口?
【发布时间】:2016-08-19 14:21:18
【问题描述】:

我需要我的一些表单类实现相同的功能。

(我已经放弃了将这个函数添加到普通锚定表单的想法,因为我不想添加对我的大多数表单无用的函数。)

所以...我考虑过使用接口。

IMyInterface = interface
  procedure ShowHello();
end;

var  
  MyForm : TMyForm;
  MyInterface : IMyInterface;
begin
  MyForm := TMyForm.Create(Self);
  MyInterface := MyForm;
  //...
end;

在这样的简单情况下,它可以正常工作,但我的应用程序使用动态包,并且我正在使用“GetClass”函数来获取表单类。 我尝试如下:

var
  MyForm : TForm;
  MyInterface : IMyInterface;
begin
  MyForm := TForm(GetClass('TMyForm').Create());
  MyInterface := MyForm;
end;

它会导致“不兼容的类型:'IMyInterface' and 'TForm'”错误。 有没有办法使用接口来实现我的目标,或者尝试其他方式会更好?

【问题讨论】:

    标签: delphi interface


    【解决方案1】:

    使用Supports函数检查接口是否实现。

    示例

    var
      MyForm : TForm;
      MyInterface : IMyInterface;
    begin
      MyForm := TFormClass(GetClass('TMyForm')).Create(...);
    
      if Supports(MyForm, IMyInterface, MyInterface) then
      begin
        MyInterface.ShowHello;
      end;
    end;
    

    您需要为您的界面声明 GUID。否则Supports 不起作用。所以接口声明应该是这样的:

    IMyInterface = interface
      ['{052E7D55-B633-4256-9084-37D797B01BB4}']
      procedure ShowHello();
    end;
    

    【讨论】:

    • 我按照建议做了,但支持结果为假。 TMyForm 类被声明为“TMyForm = class(TForm, IMyInterface)”。有什么遗漏吗?
    • 接口类型在其声明中需要一个唯一的 GUID。它有 GUID 吗?
    • 是的,我按下了 Ctrl + Shift + G 来获得一个,并将它添加到 IMyInterface 声明中。
    • 对不起!我的测试项目有一点混乱,现在“支持”结果为 True 并且 ShowHello 函数已正确执行!非常感谢您的回答!
    猜你喜欢
    • 2011-10-28
    • 2011-01-12
    • 2022-01-19
    • 2013-08-28
    • 2011-05-18
    • 2020-08-08
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多