Created
January 26, 2019 07:32
-
-
Save superswanman/c18fcf856972dd47ddc5c3ec74aedd2d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
uses | |
ForUsing; | |
type | |
TFoo = class | |
private | |
FValue: Integer; | |
public | |
constructor Create(Value: Integer); | |
destructor Destroy; override; | |
procedure Test; | |
end; | |
{ TFoo } | |
constructor TFoo.Create(Value: Integer); | |
begin | |
FValue := Value; | |
Writeln('TFoo.Create' + FValue.ToString); | |
end; | |
destructor TFoo.Destroy; | |
begin | |
Writeln('TFoo.Destroy' + FValue.ToString); | |
inherited; | |
end; | |
procedure TFoo.Test; | |
begin | |
Writeln('TFoo.Test' + FValue.ToString); | |
end; | |
// TObjectのメソッドなので、メソッド内での使用はUsingのみでOK | |
procedure TForm1.Hoge; | |
begin | |
for var obj in Using(TFoo.Create(0)) do | |
begin | |
raise EProgrammerNotFound.Create('Someone please help me!'); | |
end; // 例外が起きてもここできちんと解放されます | |
end; | |
// 本物みたいに重ね書きも可 | |
procedure Hoge; | |
begin | |
Writeln('begin'); | |
for var foo1 in TObject.Using(TFoo.Create(1)) do | |
for var foo2 in TObject.Using(TFoo.Create(2)) do | |
begin | |
foo1.Test; | |
foo2.Test; | |
end; | |
Writeln('end'); | |
end; | |
// 上の出力結果 | |
// begin | |
// TFoo.Create1 | |
// TFoo.Create2 | |
// TFoo.Test1 | |
// TFoo.Test2 | |
// TFoo.Destroy2 | |
// TFoo.Destroy1 | |
// end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment