2011-04-15 49 views
2

我想知道當訪問屬性嵌套在另一個屬性中時,訪問Delphi的後期綁定屬性或方法的正確方法是什麼。讓我解釋。如何訪問後期綁定的嵌套屬性和方法?

檢查此示例應用程序以檢查防火牆是否處於活動狀態,聲明的3個函數使用COM對象HNetCfg.FwMgr並返回相同的值。

{$APPTYPE CONSOLE} 

uses 
    Variants, 
    ActiveX, 
    Comobj, 
    SysUtils; 

//in this function i don't use any "helper" property to hold the temp value of the properties. 
function FirewallIsActive1 : Boolean; 
var 
    Firewall : OleVariant; 
begin 
    Firewall := CreateOleObject('HNetCfg.FwMgr'); 
    Result := Firewall.LocalPolicy.CurrentProfile.FirewallEnabled; 
end; 


//here i hold the value of the LocalPolicy property 
function FirewallIsActive2 : Boolean; 
var 
    Firewall : OleVariant; 
    Policy : OleVariant; 
begin 
    Firewall := CreateOleObject('HNetCfg.FwMgr'); 
    Policy := Firewall.LocalPolicy; 
    Result := Policy.CurrentProfile.FirewallEnabled; 
end; 


//Here i use a "helper" variable for each property 
function FirewallIsActive3 : Boolean; 
var 
    Firewall : OleVariant; 
    Policy : OleVariant; 
    Profile : OleVariant; 
begin 
    Firewall := CreateOleObject('HNetCfg.FwMgr'); 
    Policy := Firewall.LocalPolicy; 
    Profile := Policy.CurrentProfile; 
    Result := Profile.FirewallEnabled; 
end; 


var 
    i : Integer; 
begin 
try 
    CoInitialize(nil); 
    try 
     Writeln(BoolToStr(FirewallIsActive1,True)); 
     Writeln(BoolToStr(FirewallIsActive2,True)); 
     Writeln(BoolToStr(FirewallIsActive3,True)); 
     Readln; 
    finally 
     CoUninitialize; 
    end; 
except 
    on E:Exception do 
    begin 
     Writeln(E.Classname, ':', E.Message); 
     Readln; 
    end; 
    end; 
end. 

我問這個問題,因爲我想知道,如果Delphi編譯器能夠生成代碼處置olevariants中的3個功能無論如何?

回答

6

德爾福不會生成任何額外的變種,因此不會有任何問題來釋放它們。德爾福只會遍歷IDispatch路線以獲得FirewallIsActive1中的值。

如果你只需要一個值,我更喜歡這個。如果你需要嵌套接口的幾個信息,我會把它存儲在一個輔助變量中。