This is a creation in Article, where the information may have evolved or changed.
When implementing a function, if the intermediate steps go wrong, you need to release the resources and exit the function, which is cumbersome and error-prone. The go language author is disappointed with the experience of software development over the past decade, and in response to this problem, he brings the defer method that allows you to exit anywhere within the function to make sure you have a chance to clean up. A similar approach can be implemented in Delphi XE. Program Demo_defer;
{$APPTYPE CONSOLE}
Uses
Sysutils,
Coroutineunit; Or use this unit ... It's still in the annex.
Begin
Tproc (procedure ()//This function demonstrates copying the contents of a file into another file.
Var
F1, F2:integer; Two file pointers, F1 content to be copied into the F2.
Begin
F1:=fileopen (' F1 ', fmopenread); Open F1 file
The defer (procedure ()//defer function saves the parameter function and then calls it when the function it belongs to exits.
Begin
FileClose (F1);
Writeln (' F1 is closed ');
End);
F2:=fileopen (' F2 ', fmopenwrite); Open F2 file again
If F2=-1 then BEGIN
Writeln (' F2 open failed ');
Exit; Take a decisive exit without considering the state of F1
End
Copycontent (F1, F2); Start copy (assuming this copy function exists)
FileClose (F2);
End) ();
READLN;
End.
In the past, when dealing with this situation, you need to determine whether F2 open fails, if it fails, you need to close F1 and then exit, if this function is complex, you may forget to close, and in this way, make sure that no matter how many exits you write, the code that closes F1 is executed.
The result of the actual output is:
F2 Open failed
F1 is closed.
Related downloads:
Examples of defer methods using the Go language in Delphi XE
Source: HTTP://WWW.CNPACK.ORG/SHOWDETAIL.PHP?ID=699&LANG=ZH-CN