如何在Delphi中共享功能?

Mik*_*ail 3 delphi delphi-7

例如,我为我的表单编写了几个函数.现在,我需要另一种形式的完全相同的功能.那么,我如何在两种形式之间分享它们呢?如果可能的话,请提供一个简单的例子.

Ken*_*ite 12

不要把它们放在你的表格中.将它们分开并将它们放在一个公共单元中,然后将该单元添加到uses需要访问它们的子句中.

这是一个快速示例,但您可以看到许多Delphi RTL单元(例如SysUtils).(您应该学会使用VCL/RTL源代码以及Delphi中包含的演示应用程序;他们可以比在此等待答案更快地回答您发布的许多问题.)

SharedFunctions.pas:

unit 
  SharedFunctions;

interface

uses
  SysUtils;  // Add other units as needed

function DoSomething: string;

implementation

function DoSomething: string;
begin
  Result := 'Something done';
end;

end.
Run Code Online (Sandbox Code Playgroud)

UnitA.pas

unit
  YourMainForm;

uses
  SysUtils;

interface

type
  TMainForm = class(TForm)   
    procedure FormShow(Sender: TObject);
    // other stuff
  end;

implementation

uses
  SharedFunctions;

procedure TMainForm.FormShow(Sender: TObject);
begin
  ShowMessage(DoSomething());
end;

end.
Run Code Online (Sandbox Code Playgroud)

在Delphi的最新版本中,您可以在Delphi 7中创建函数/方法record:

unit
  SharedFunctions;

interface

uses
  SysUtils;

type
  TSharedFunctions = record
  public
    class function DoSomething: string;
  end;

implementation

function TSharedFunctions.DoSomething: string;
begin
  Result := 'Something done';
end;

end;
Run Code Online (Sandbox Code Playgroud)

UnitB.pas

unit
  YourMainForm;

uses
  SysUtils;

interface

type
  TMainForm = class(TForm)   
    procedure FormShow(Sender: TObject);
    // other stuff
  end;

implementation

uses
  SharedFunctions;

procedure TMainForm.FormShow(Sender: TObject);
begin
  ShowMessage(TSharedFunctions.DoSomething());
end;

end.
Run Code Online (Sandbox Code Playgroud)