微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Delphi中声明公共全局变量

假设我在delphi项目中有两种形式,我想要能够从form2访问form1的变量.有没有人可以申报,在form1中说一个’public’变量,可以从所有表单中读取?

我已经尝试在公共声明中放一个变量

{ private declarations }
  public
    { public declarations }
  test: integer;
  end;

在形式2我有

unit Unit2;

{$mode objfpc}{$H+}

interface

uses
  Classes,SysUtils,FileUtil,Forms,Controls,Graphics,Dialogs,unit1;

type

  { TForm2 }

  TForm2 = class(TForm)
    procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
    procedure FormCreate(Sender: TObject);
  private
    { private declarations }
  public
    { public declarations }
  end; 

var
  Form2: TForm2; 
implementation

{$R *.lfm}

{ TForm2 }

procedure TForm2.FormCreate(Sender: TObject);
begin
  form1 //<---------- DOES NOT GET RECOGNIZED
end;

end.

然后我将“Unit1”放入Form2的使用部分,但由于循环引用,我似乎无法做到这一点.如果可能,我想避免使用指针.

解决方法

首先,如果您必须使用全局变量(Craig明智地指出,最好不要使用全局变量),那么您应该将要共享的全局变量放在SharedGlobals.pas中:
unit SharedGlobals;
interface
var
   {variables here}
   Something:Integer;
implementation
    { nothing here?}

现在使用这个单元,从你想要共享访问这个变量的两个单元.或者,有两个引用另一个对象,它被命名为一些明智的东西,并将该对象设计为状态(变量值)的持有者,这两个实例(表单或类,或任何)需要共享.

第二个想法,由于你的两个单元你已经有依赖关系,所以你也可以通过使用创建循环依赖关系的单元来实现循环依赖,从实现部分而不是接口:

unit Unit2;
 interface
   /// stuff
 implementation
    uses Unit1;

unit Unit1;
 interface
   /// stuff
 implementation
    uses Unit2;

原文地址:https://www.jb51.cc/delphi/102719.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐