2013-04-24 62 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.