Tre*_*tBG 3 delphi circular-dependency delphi-units
我想从一个从main调用的类中访问一个主窗体变量.像这样的东西:
单元1:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,Unit2, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
public
end;
var
Form1: TForm1;
Chiled:TChiled;
const
Variable = 'dsadas';
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
Chiled.ShowMainFormVariable;
end;
end.
Run Code Online (Sandbox Code Playgroud)
单元2:
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
type
TChiled = class
private
public
procedure ShowMainFormVariable;
end;
var
Form1: TForm1;
implementation
procedure TChiled.ShowMainFormVariable;
begin
ShowMessage(Form1.Variable);
end;
end.
Run Code Online (Sandbox Code Playgroud)
如果在Unit2中我添加使用Unit1弹出一个圆形错误.
如何使Unit1成为全球?
正如其他答案所述,您应该使用实现部分中的一个单元.
假设你在'unit2'中选择了你在实现中使用'unit1'.那么你需要设计一种机制来告诉'TChiled'如何访问'Form1'.那是因为你没有在'unit2'的接口部分使用'unit1',你不能在接口部分声明'Form1:TForm1'变量.以下只是一种可能的解决方案:
unit2
type
TChiled = class
private
FForm1: TForm;
public
procedure ShowMainFormVariable;
property Form1: TForm write FForm1;
end;
implementation
uses
unit1;
procedure TChild.ShowMainFormVariable;
begin
ShowMessage((FForm1 as TForm1).Variable);
end;
Run Code Online (Sandbox Code Playgroud)
然后在unit1中,您可以在调用TChiled的方法之前设置TChiled的Form1属性:
procedure TForm1.Button1Click(Sender: TObject);
begin
Chiled.Form1 := Self;
Chiled.ShowMainFormVariable;
end;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4502 次 |
| 最近记录: |