在Delphi中声明公共全局变量
发布时间:2020-12-15 10:10:00 所属栏目:大数据 来源:网络整理
导读:假设我在delphi项目中有两种形式,我想要能够从form2访问form1的变量.有没有人可以申报,在form1中说一个’public’变量,可以从所有表单中读取? 我已经尝试在公共声明中放一个变量 { private declarations } public { public declarations } test: integer; e
假设我在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; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |