Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
927 views
in Technique[技术] by (71.8m points)

split - Put class functions to multiple units in Delphi?

I am using Delphi XE3. Currently there are too many functions in my unit, and one of them is very long. So I want to put that long function to another unit. Is that possible?

I try as follows:

Unit1:

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    procedure Test;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}
...

Unit2:

unit Unit2;

interface

implementation

uses Unit1;

procedure TForm1.Test;
begin
end;

end.

But compile fails, said "[dcc32 Error] Unit1.pas(16): E2065 Unsatisfied forward or external declaration: 'TForm1.Test'"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You cannot move a class method's implementation to another unit. However, you can refactor its inner code into its own function in another unit, and then call that function from your class method, eg:

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    procedure Test;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses
  Unit2;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Test;
end;

procedure TForm1.Test;
begin
  Unit2.DoTest;
end;

end.
unit Unit2;

interface

procedure DoTest;

implementation

procedure DoTest;
begin
  ...
end;

end.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...