簡體   English   中英

從Delphi的子單元訪問主表單

[英]Access main form from child unit in Delphi

我想從一個從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.

單元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成為全球?

正如其他答案所述,您應該使用實現部分中的一個單元。

假設你在'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;

然后在unit1中,您可以在調用TChiled的方法之前設置TChiled的Form1屬性:

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

最簡單的解決方案是將Unit1添加到Unit2的實現部分中的uses子句,因為這會繞過循環引用。

但是我建議這個設計是有缺陷的。 很難看到您嘗試使用示例代碼實現的目標,因此很難提供任何真正的建議。

好吧,簡單的天真答案是你應該將Unit1添加到Unit2實現部分的uses子句中:

unit Unit2;
......
implementation

uses
  Unit1;
.....

您不能將它添加到Unit2的接口部分中的uses子句,因為這將在接口部分創建循環引用。 為了話,接口Unit1會使用Unit2和接口Unit2將使用Unit1 該語言不允許這樣做。 常見的解決方案是在實現級別use其中一個單元。


話雖如此,您的代碼相當混亂,並在許多其他方面失敗。 您的問題比循環引用更深入。 例如, Form1.Variable是什么意思? 常量Variable不是TForm1的成員。 您聲明了兩個名為Form1的全局變量TForm1類型。 你為什么那樣做?

此外,你拼錯了孩子。

我通常創建一個數據模塊(或任何類型的非可視容器)來共享全局變量。 這樣,兩個單元都可以在沒有循環引用的情況下使用變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM