/ / メモ
2007-12-17

using 文は D言語の scope(exit) 文に似た機能を持っている。

C# 言語仕様の208ページにから引用

using System;
using System.IO;
class Test
{
    static void Main() {
    using (TextWriter w = File.CreateText("log.txt")) {
        w.WriteLine("This is line one");
        w.WriteLine("This is line two");
    }
    using (TextReader r = File.OpenText("log.txt")) {
        string s;
        while ((s = r.ReadLine()) != null) {
            Console.WriteLine(s);
        }
    }
}
}

これを D言語 で書くと、

void main(){
    {
        File w = new File("log.txt",FileMode.Out);
        scope(exit) w.close();
        w.writeLine("This is line one");
        w.writeLine("This is line two");
    }

    {
        File r = new File("log.txt",FileMode.In);
        scope(exit) r.close;
        char[] s;
        while ((s =r.readLine()) != "") {
            writefln(s);
        }
    }

こんな感じだろうか?
finally を書かなくてすむ。

トラックバック http://mikanya.dip.jp/memo/2007-12-17-2