2013-04-24 25 views
2

我想将“self”作为参数传递给另一个类(以不同的单元)的方法。然而,第一类的类型在第二类中是未知的,因为我不能将第一单元放入第二单元的使用部分。所以我将参数类型定义为指针,但是当我尝试从第一个类调用一个方法时,Delphi 7解析器告诉我该classtyp是必需的。在德尔福传递自己作为参数

那么我该如何解决这个问题呢?

+0

听起来像一个界面的工作。作为一种混合物,在'B'在界面中使用'A'并且'A'在实现中使用'B'的情况下允许循环引用。这几乎总是一个坏主意,头脑。 – 2013-04-24 11:03:19

+1

如果在实现部分的使用中声明第二个单元会怎么样? – 2013-04-24 11:06:10

+1

只需使用'TObject'作为参数,而不是第一个类的指针和父类。 – valex 2013-04-24 11:07:15

回答

6

通过使实现部分中已知的类可以投射给定的参考。

unit UnitY; 

interface 
uses Classes; 
type 
    TTest=Class 
     Constructor Create(AUnKnowOne:TObject); 
    End; 



implementation 
uses UnitX; 
{ TTest } 

constructor TTest.Create(AUnKnowOne: TObject); 
begin 
    if AUnKnowOne is TClassFromUnitX then 
     begin 
     TClassFromUnitX(AUnKnowOne).DoSomeThing; 
     end 
    else 
     begin 
     // .... 
     end; 
end; 

end. 
4

我喜欢这种类型的问题的接口方法。除非你的单位紧密耦合,在这种情况下,他们应该共享一个单元,接口是交换类的相关部分的完整方式,而不必具有每种类型的完整知识。

考虑:

unit UnitI; 
interface 
type 
    IDoSomething = Interface(IInterface) 
    function GetIsFoo : Boolean; 
    property isFoo : Boolean read GetIsFoo; 
    end; 
implementation 
end. 

unit UnitA; 
interface 
uses UnitI; 
type 
    TClassA = class(TInterfacedObject, IDoSomething) 
    private 
     Ffoo : boolean; 
     function GetIsFoo() : boolean; 
    public 
     property isFoo : boolean read GetIsFoo; 
     procedure DoBar; 
     constructor Create; 
    end; 
implementation 
uses UnitB; 

constructor TClassA.Create; 
begin 
    Ffoo := true; 
end; 

function TClassA.GetIsFoo() : boolean; 
begin 
    result := Ffoo; 
end; 

procedure TClassA.DoBar; 
var SomeClassB : TClassB; 
begin 
    SomeClassB := TClassB.Create; 
    SomeClassB.DoIfFoo(self); 
end; 

end. 

,并注意TClassB不必知道TClassA或包含它的单元东西 - 它只是接受由​​遵守任何对象界面合同。

unit UnitB; 
interface 
uses UnitI; 
type 
    TClassB = class(TObject) 
    private 
     Ffoobar : integer; 
    public 
     procedure DoIfFoo(bar : IDoSomething); 
     constructor Create; 
    end; 

implementation 

constructor TClassB.Create; 
begin 
    Ffoobar := 3; 
end; 

procedure TClassB.DoIfFoo(bar : IDoSomething); 
begin 
    if bar.isFoo then Ffoobar := 777; 
end; 

end.