Delphi 在表单上使用单元程序

Delphi Using unit procedure on form

我正在学习 OOP,到目前为止我已经创建了一个基本程序。我已经创建了自己的类:

Type
Zombie = class
  private
   fLife : Integer;
   fAge : Integer;
   fHeight: String;
  public
   Constructor Create(pLife, pAge : Integer; pHeight : String);
   Procedure SetLife(pLife : Integer);
   function GetLife : Integer;
   Procedure ShowLife;
end;

ShowLife 程序完全如其所说:

procedure Zombie.ShowLife;
begin
ShowMessage(inttostr(fLife));
end;

我试图在表单上调用此过程,但它显示未声明的标识符:

procedure Tform1.ShowLifebtnClick(Sender: TObject);
begin
Zombies_Unit.ShowLife;
end;

我已将单位包含在表格的用户中。如何在另一种形式上使用方法

您必须创建 class 的实例并调用该对象的方法,如

MyZombie := Zombie.create(20,15);
MyZombie.ShowLife;
...
MyZombie.free;

从手机发送,无法格式化代码。

EDIT/SUPPLEMENT:

由于我的简短回答似乎适合技术不良习惯(对此我感到抱歉)我想向提问者添加以下建议:

请使用 Try/Finally 结构来避免在 create() 和 free() 之间发生错误时对象没有被删除,就像 Zdravko Danev 的回答指出的那样。使用通用命名约定使您的代码更易于理解也很有意义(例如 TZombie 作为 class 名称)。

您需要创建并释放您使用的对象 before/after。图案是这样的:

MyZombie := TZombie.Create(10, 20, 30); 
try
  MyZombie.ShowLife(); 
finally
  MyZombie.Free();
end;

你必须注意一件事:你的class和你的表格在同一个文件里?如果答案是否定的,您必须在表单文件的 uses 中声明单位名称,例如:

unit MyUnit;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs;

type
  TMyForm = class(TForm)
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  MyForm: TMyForm;

implementation

uses unitzombie; //The name unit where is your class

{$R *.dfm}

end.

解决这个小问题后,您必须在调用此方法之前创建您的对象:

procedure Tform1.ShowLifebtnClick(Sender: TObject);
var 
   Zombi: Zombie; 
begin
      Zombi := Zombie.Create(5,10,15);
   try
      Zombi.ShowLife;
   finally
      Zombi.Free;
   end;
end;