且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Delphi中安全地创建和释放多个对象

更新时间:2023-11-23 07:54:22

您如果首先给变量赋nil,就可以用一个try块来做到这一点,

You can do this with one try block if you assign nil to the variables first like,

newOrderSource := nil;
twData := nil;
webData := nil;
try
  newOrderSource := TWebNewOrderSource.Create();    
  twData := TTWData.Create();    
  webData := TWebData.Create();    

  //do stuff    
finally    
  webData.Free();    
  twData.Free();    
  newOrderSource.Free();    
end;    

之所以有效,是因为 Free()检查自我 nil

This works because Free() checks Self for nil.