2013-08-30 17 views
0

我有一個名爲ISupport的接口,用於提供技術支持信息。如何發現具體的類對象已經在TInterfaceList中?

ISupport = Interface(IInterface) 
    procedure AddReport(const Report: TStrings); 
End; 

每個具有用於支持實現該接口相關的信息,並在構造函數調用類:使用的

procedure TySupport.RegisterSupport(Support: ISupport); 
begin 
    if FInterfaceList.IndexOf(Support) = -1 then 
    FInterfaceList.Add(Support); 
end; 

實施例(部分):

TyConfig = class(TInterfacedObject, ISupport) 
private 
    procedure AddReport(const Report: TStrings); 

public 
    constructor Create; 
end; 

constructor TyConfig.Create; 
begin 
    if Assigned(ySupport) then 
    ySupport.RegisterSupport(Self); 
end; 

上的代碼後來我可以查看列表並調用AddReport。

我的問題是,有一個類,這個TyConfig,它被多次實例化,它會報告的信息是完全一樣的。 FInterfaceList.IndexOf只避免添加相同的接口。

我想避免來自TyConfig的ISupport獲得多次註冊。

+2

相關信息[如何在Delphi中將接口轉換爲對象](http://stackoverflow.com/q/4138211/1699210) – bummi

回答

2

從德爾福2010年開始,可以從一個接口轉換爲一個對象:

var 
    obj: TObject; 
    intf: IInterface; 
.... 
obj := intf as IInterface; 

一旦你的能力,這是一小步,檢查對象從特定類派生:

if obj is TyConfig then 
    .... 

有了這些作品,您應該能夠解決您的問題。

+0

在D2010之前,您可以使用RTL的'IInterfaceComponentReference'接口爲' TComponent'。創建另一個接口,比如'ITyConfigReference',其唯一目的是返回'TyConfig'對象的'Self'指針,然後'TyConfig'實現'ITyConfigReference'和'ISupport'。這樣,您可以查詢「ITyConfigReference」的任何'ISupport'接口,如果支持,則可以根據需要使用它來檢索'TyConfig'對象指針。或者,僅僅支持'ITyConfigReference'這一事實足以知道對象是否是'TyConfig'。 –

相關問題