delphi - 从 Delphi 的子单元访问主窗体

标签 delphi circular-dependency delphi-units

我想从主窗体调用的类访问主窗体变量。 像这样的事情:

单元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.

单元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.

如果在 Unit2 中我添加到使用 Unit1 中,则会弹出循环错误。

如何使Unit1成为GLOBAL?

最佳答案

正如其他答案所说,您应该使用实现部分中的单元之一。

假设您选择“unit2”,您将在实现中使用“unit1”。那么您需要设计一种机制来告诉“TChiled”如何访问“Form1”。这是因为由于您没有在“unit2”的接口(interface)部分中使用“unit1”,因此您无法在接口(interface)部分中声明“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;

然后在unit1中你可以在调用TChiled的方法之前设置TChiled的Form1属性:

procedure TForm1.Button1Click(Sender: TObject);
begin
  Chiled.Form1 := Self;
  Chiled.ShowMainFormVariable;
end;

关于delphi - 从 Delphi 的子单元访问主窗体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10174239/

相关文章:

windows - 获取主题编辑控件的非客户区的大小

python - 在 Python 中使用相互或循环(循环)导入时会发生什么?

C中函数指针typedef的循环引用

delphi - 在光标处打开文件未在 IDE 中打开文件

delphi - delphi中的单位与其他语言中的类相同吗?

xml - 需要支持D2009的xml组件

delphi - 第二次分配 TPngImageCollectionItem 对象 TreeView 仍然绘制第一个分配的图像(Delphi XE 7)

delphi - 如何从 IIS ISAPI 的 GetExtensionVersion 中获取我网站的 URL?

C++ 游戏 - 发出父类信号,循环依赖问题

delphi - 如何从VCL重新编译特定单元?