私は C# でコーディングしており、'using' ブロックで使用したいクラスを作成しました。
これは可能ですか?可能であれば、どのように進めればよいですか?クラスに何を追加する必要がありますか?
私は C# でコーディングしており、'using' ブロックで使用したいクラスを作成しました。
これは可能ですか?可能であれば、どのように進めればよいですか?クラスに何を追加する必要がありますか?
このusing
キーワードは、 を実装する任意のオブジェクトで使用できますIDisposable
。を実装するには、クラスにメソッドを含めますIDisposable
。Dispose
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()) {
}
}
public class MyClass : IDisposable
{
public void Dispose()
{
}
}
それだけです!コードを呼び出すと、次のことができます。
using(var mc = new MyClass())
{
}