3

私は C# でコーディングしており、'using' ブロックで使用したいクラスを作成しました。

これは可能ですか?可能であれば、どのように進めればよいですか?クラスに何を追加する必要がありますか?

4

2 に答える 2

4

このusingキーワードは、 を実装する任意のオブジェクトで使用できますIDisposable。を実装するには、クラスにメソッドを含めますIDisposableDispose

DisposeライブラリのユーザーがDispose.

例えば:

class Email : IDisposable {

    // The only method defined for the 'IDisposable' contract is 'Dispose'.
    public void Dispose() {
        // The 'Dispose' method should clean up any unmanaged resources
        // that your class uses.
    }

    ~Email() {
        // You should also clean up unmanaged resources here, in the finalizer,
        // in case users of your library don't call 'Dispose'.
    }
}

void Main() {

    // The 'using' block can be used with instances of any class that implements
    // 'IDisposable'.
    using (var email = new Email()) {

    }
}
于 2012-11-26T18:00:53.680 に答える
0
public class MyClass : IDisposable
{
    public void Dispose()
    {
    }
}

それだけです!コードを呼び出すと、次のことができます。

using(var mc = new MyClass())
{
}
于 2012-11-26T18:02:40.373 に答える