名前空間に使うusingって予約語の命令。
でも、C#のusingってのは同じ名前で別の動きをするんだね。
とりあえず、利点はこんなとこ?
- IDisposableインターフェースで定義されているDispose()メソッドを勝手に呼んでくれる
ってなことでこんなクラスを準備。
IDisposableインターフェースを継承しているとこがミソだそうな。
class Temporary : IDisposable
{
// コンストラクタ
public Temporary()
{
System.Console.WriteLine("Temporary.Temporary()");
}
// わざと例外を発生する
public void Funtion()
{
System.Console.WriteLine("Temporary.Function()");
throw new Exception("Excepion!!");
}
// オブジェクトを破棄する
public void Dispose()
{
System.Console.WriteLine("Temporary.Dispose()");
}
}
んで、呼び出す方。
処理としてはこんな順番。
- try-catchだけで呼び出す
- usingで囲って呼び出す
- usingで囲ったうえで例外を無理やり発生させる
んで、コードはこんな感じ。
// try-catch only
System.Console.WriteLine("--- try catch only ---");
try
{
Temporary temporary = new Temporary();
}
catch(Exception ex)
{
System.Console.WriteLine(ex.Message);
}
// using
System.Console.WriteLine("--- using ---");
using (Temporary temporary = new Temporary())
{
try
{
; // 何もしない
}
catch(Exception ex)
{
System.Console.WriteLine(ex.Message);
}
}
// using with exception
System.Console.WriteLine("--- using with exception ---");
using (Temporary temporary = new Temporary())
{
try
{
temporary.Funtion();
}
catch (Exception ex)
{
System.Console.WriteLine(ex.Message);
}
}
実行してみると、結果はこんな感じ。
usingで囲ったとこは例外ありなし関係なくDispose()メソッドが呼ばれる。
使いどころはオブジェクトの開放あたりがメジャーな感じ。
ちなみに、IDisposableインターフェースを継承してないクラスをusingで囲うと、こんな感じで起こられてコンパイルエラーになる。
using ステートメントで使用される型は、暗黙的に 'System.IDisposable' への変換が可能でなければなりません。
んまま、メモってことで。
