【问题标题】:How to pass a method function to another Object?如何将方法函数传递给另一个对象?
【发布时间】:2021-04-28 16:51:45
【问题描述】:

如何将方法函数传递给另一个对象?在 Delphi 中这样的事情是可能的吗?

例如,我正在尝试在 DataModule 中创建一个 PopupMenu,因为此 PopupMenu 将在应用程序的多个位置使用。

PopupMenu 将使用特定函数,例如:GetCustomer(),它返回 TCustomer,可以在其上执行各种操作。

创建和使用 DataModule 的每个表单/框架都希望将 GetCustomer() 的自定义实现传递给它。

我想写这样的东西:

TGetCustomerFunc = function: TCustomer of object;

然后在 DataModule 上创建一个字段/属性:

TPopupDataModule = class(TDataModule)
public
  { Public declarations }
  GetCustomer: TGetCustomerFunc;
end;

GetCustomer 将被创建PopupDataModule 的每个框架分配一个方法,并具有自己的特定实现。

但是,function: TCustomer of object; 的语法无效。

有什么建议可以解决这个问题吗?

【问题讨论】:

  • “但是,function: TCustomer of object; 不是有效的语法。”。是的,它完全有效。
  • @lurker: function: TCustomer 是一个返回 TCustomer 的无参数函数,而 function: TCustomer of object 是一个返回 TCustomer 的无参数方法(因此,它有一个隐藏的 Self 参数)。
  • @AndreasRejbrand 谢谢,我不熟悉那种语法。
  • @AndreasRejbrand:你说得很对。我的错。不知何故,它没有一次编译,可能是因为我的语法不正确。
  • @RaelB 显示的代码完全有效。那么为什么你认为不是呢?您是否收到编译器错误?如果是这样,究竟是什么错误?请提供minimal reproducible example

标签: oop delphi


【解决方案1】:

您最初的问题:如何将方法函数传递给另一个对象?

您可以为您的函数或过程原型声明一个类型,然后像传递任何其他变量一样传递它。查看在 RTL、VCL 和 FMX 中使用 TNotifyEvent 的示例,了解如何做到这一点。

这样的事情可能吗?是的。

我不清楚你的用例到底是什么,所以我不确定给你最好的例子。你说你想使用TDataModule 来创建TPopupMenu,这似乎很清楚,但你随后声明TCustomer 需要由调用它的TFrameTForm 对象提供。

为什么不直接将TCustomer 对象传递给它呢?传递一个函数来获取一个对象似乎有点令人费解。

如果我明白你在寻找什么,你会想要这样的东西:

interface

  type
  TCustomer = class(TObject);
  TGetCustomerFunc = function(): TCustomer of Object;

  TPopupDataModule = class(TDataModule)
  public
    function BuildPopupMenu(fnGetCustomer: TGetCustomerFunc): TPopupMenu;
    ...
  end;

implementation

  function TPopupDataModule.BuildPopupMenu(fnGetCustomer: TGetCustomerFunc): TPopupMenu;
  var
    pCustomer: TCustomer;
  begin
    if(Assigned(fnGetCustomer)) then
    begin
      pCustomer:=fnGetCustomer();
      ...
    end;
  end;

要调用它,您可以在调用它的对象中传递函数的地址。因此,如果您在表单中定义:

  protected
    function GetTheCustomer(): TCustomer;

您可以像这样将此例程传递给 TPopupDataModule:

  { pPopupDM:=TPopupDataModule.Create(Application); // called previously }
  pPopupDM.BuildPopupMenu(Self.GetTheCustomer);    // in a Form method Self is the form

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 2019-02-19
    • 2017-06-03
    • 1970-01-01
    • 2021-09-23
    相关资源
    最近更新 更多