关于普通班级的问题

时间:2011-09-24 18:55:26

标签: delphi delphi-xe2

首先,对不起标题,但很难用几句话解释好。 那问题就是这个问题。我有两个类(对象):Tclass1和Tclass2。它们与它们无关,并且两个类(对象)都调用第三个类(对象):例如Tclass3。 因为我可以在Tclass1和Tclass2之间共享Tclass3的信息?

尝试用示例更好地解释:

Tclass1 = class
private
  class3: Tclass3;
public
  property err: Tclass3 read class3 write class3;
  ...
end;

Tclass2 = class
private
  class3: Tclass3;
public
  property err: Tclass3 read class3 write class3;
  ...
end;

Tclass3 = class
private
  icode: word;
public
  property code: word read icode;
  ...
end;

主程序是:

var
  class1: Tclass1;
  class2: Tclass2;
begin
  class1 := Tclass1.create;
  try
    class2 := Tclass2.create;
    try
      class2.err := class1.err;  // <--- problem is here
         ...
         ... // processing...
         ... 
      class1.err := class2.err;  // <--- problem is here
      writeln (class1.err.code)      
    finally
      class2.free; 
    end;
  finally
    class1.free;
  end;
end;

当然,在Tclass1和Tclass2中,我调用了Tclass3的create方法并将其实例化。现在,当我运行它,做一个例外,但我无法读取它因为控制台快速关闭。 我已经应用了一个类(对象)相同的变量规则;事实上,如果我使用变量来放置它,一切正常。 不可能用类(对象)解决相同的问题? 再次感谢。

2 个答案:

答案 0 :(得分:4)

你的问题有点模糊。但是让我试着去理解。

  1. 您有两个类,它们拥有第三个类的实例。 (他们负责创建和删除课程。)
  2. 您希望在两个类之间共享信息(但不是类本身)。
  3. 在这种情况下,您可以创建一个Assign方法,将一个对象的字段复制到另一个对象:

    Tclass3 = class
    private
      icode: word;
    public
      procedure Assign(const AValue: TClass3); virtual;
    
      property code: word read icode;
      ...
    end;
    
    procedure TClass3.Assign(const AValue: TClass3);
    begin
      Assert(AValue<>nil);
      icode := AValue.icode;
    end;
    

    如果要在两者之间共享同一个对象,则需要确定哪个类拥有该对象。 (或者您甚至可以创建一个单独的所有者)。但更好的解决方案是使用TClass3的接口,这样您就可以利用引用计数。

答案 1 :(得分:1)

  

“现在当我运行它时,做一个例外,但我无法阅读它   控制台快速关闭。“

您可以按如下方式解决该问题:

在控制台应用程序的.dpr文件中,您可能会遇到以下情况:

begin
  try
    // do stuff
  except
    on e:Exception do
      writeln(e.message);
  end;
end.

只需将其更改为:

begin
  try
    // do stuff
  except
    on e:Exception do
    begin
      // show error, and wait for user to press a key
      writeln(e.message);
      readln;
    end;
  end;
end.

这应该使调试更容易。

相关问题