【问题标题】:Delphi: How to access variable in the Parent class from another parent class?Delphi:如何从另一个父类访问父类中的变量?
【发布时间】:2011-12-06 22:49:32
【问题描述】:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, IdTCPClient;

type
  TForm1 = class(TForm)
  procedure FormCreate(Sender: TObject);
  public
    Flist : TList;
    property list : TList read Flist write Flist;
  end;

  Tmy_class = class(TThread)
    public
    procedure test;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure Tmy_class.test;
begin
  // Error here, can't access the Flist var or list propertie, help !! How to access?
  TForm1(TList).list.Clear;

  // Error
  Form1.list.Clear;

  // Error
  Form1.Flist.clear;

  // HOW ????????
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Flist := FList.Create;
end;

end.

如何访问“Flist”变量? 谢谢。

德尔福 2010、印地 10、Win7

是的,这让我大开眼界: 您的帖子没有太多上下文来解释代码部分;请更清楚地解释您的情况。

【问题讨论】:

  • 你需要使用getter和setter。如果是java。它不是。我确信你的语言有类似的方式来做类似的事情。
  • 您发布的代码没有任何意义。你还没有创建x 的实例,所以你当然不能从y.test 访问它。此外,您有无法编译的代码 - x(TList).F1.Clear 的行甚至不会通过编译器,更不用说任何工作。请编辑您的帖子并添加真实的可编译代码,以演示您要解决的问题。如果不是,我投票决定将其关闭为“不是一个真正的问题”。
  • @waza - 你已经得到了帮助。阅读肯的评论。如果你有一个“x”的实例,你可以调用 someX.fl.Clear。
  • @Sertac Akyuz 我编辑了主代码,你能举个例子吗?

标签: delphi scope


【解决方案1】:

您需要处理变量 Form1。

Form1.list.clear;

但是从线程中执行此操作并不安全。

更新:编译正常。

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,     Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
 private
    { Private declarations }
    FList : TList;
  public
    { Public declarations }
    property List : TList read FList;
  end;

Type TMyClass = class(TThread)
  Public
    PROCEDURE Test;
end;
var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
  FList:= TList.Create;  // Look here how to create the list
end;

{ TMyClass }

procedure TMyClass.Test;
begin
  Form1.List.Clear;
end;

end.

但正如我之前警告过的,直接从线程中使用 List 并不是一个好主意。

另请参阅如何创建列表的评论。

是的,TMyClass 必须在某个地方正确启动。

【讨论】:

  • 我本来不想用'var Form1: TForm1;',但觉得别无选择。为什么从线程全局 TList 中使用不是一个好主意?
  • 您不应该直接从线程访问任何 VCL 类,因为它们不是线程安全的。有一些方法可以通过关键部分保护列表。或者使用线程安全列表。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多