Delphi:过程中未声明的标识符

Delphi: Undeclared Identifier in Procedure

我想在程序中编辑一个 属性 形状。 但是,如果我创建自己的程序,我会收到 "undefinded identifier" 错误。

我尝试在我的表单的 OnCreate 事件过程中编辑 属性,并且效果很好。

为什么会这样,我该如何解决?

unit Unit1;

interface

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

type
    Tfrm_main = class(TForm)            
    shp_wheelLeftInside: TShape;
    shp_wheelRightInside: TShape;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }

  public
    { Public declarations }
  end;

var
  frm_main: Tfrm_main;

implementation

{$R *.dfm}

procedure addWheelInsides();
begin

    shp_wheelRightInside.Height := 42;           //this is where the error occurs

end;

procedure Tfrm_main.FormCreate(Sender: TObject);
begin

   shp_wheelLeftInside.Height := 42;
   shp_wheelRightInside.Height := 42;

  addWheelInsides();

end;

end.

shp_wheelRightInside 字段在您的程序中不可见。 在表单内声明过程 addWheelInsides() 作为方法来解析 shp_wheelRightInside 范围。

type
    Tfrm_main = class(TForm)            
    shp_wheelLeftInside: TShape;
    shp_wheelRightInside: TShape;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
    procedure addWheelInsides;

  public
    { Public declarations }
  end;

如果您想将程序扩展到多个单元,请改为将 TShape 作为参数传递。

问题是 shp_wheelRightInside 是一个属于您的 Tfrm_main class 的字段,而您声明的 addWheelInsides() 方法是属于的裸普通方法什么都没有。因此,该方法无权访问属于表单的字段。

一个解决方案是将打算对表单拥有的对象进行操作的方法移动到表单本身。

  Tfrm_main = class(TForm)            
    shp_wheelLeftInside: TShape;
    shp_wheelRightInside: TShape;
    procedure FormCreate(Sender: TObject);
  private
    procedure addWheelInsides();  {declare it here}    
  public
    { Public declarations }
  end;

然后将其作为 class 形式的方法实现为 :

procedure Tfrm_main.addWheelInsides();
begin    
  shp_wheelRightInside.Height := 42;   
end;