public void Func() {
using (FileStream fs = new FileStream("test.txt", FileMode.Read)) {
using (StreamReader sr = new StreamReader(fs)) {
// 処理する
}
}
}
このコードは下記のコードとまったく同じ意味です。実際、これらのコードのILを見比べると100%まったく同じです。
ということなんですよ。興味深いなぁ。知らなかったなぁ、usingにこんな機能があるなんて。System.Windows.Forms.FormクラスももちろんIDisposableインターフェースが組み込まれているわけですが、例えば次のようなことをやると、即Dispose()メソッドが走ります。気をつけてね。(w
public void Func() {
FileStream fs = new FileStream("test.txt", FileMode.Read);
try {
StreamReader sr = new StreamReader(fs);
try {
// 処理する
}
finally {
if (sr != null) {
sr.Dispose();
}
}
}
finally {
if (fs != null) {
fs.Dispose();
}
}
}
public class Form1 : System.Windows.Forms.Form
{
}
public class Sample
{
using(Form1 form = new Form1())
{
form.Show();
}
// 上のブロックが終わるときにDispose()が走るので、
// 折角ShowしたFormが消えるのだ。(w
}
Comments