Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# 2008 Step by Step.pdf
Скачиваний:
26
Добавлен:
25.03.2016
Размер:
13.96 Mб
Скачать

266 Part II Understanding the C# Language

Calling the Dispose Method from a Destructor

When writing a class, should you write a destructor or implement the IDisposable interface? A

call to a destructor will happen, but you just don’t know when. On the other hand, you know exactly when a call to the Dispose method happens, but you just can’t be sure that it will ac-

tually happen, because it relies on the programmer remembering to write a using statement. However, it is possible to ensure that the Dispose method always runs by calling it from the destructor. This acts as a useful backup. You might forget to call the Dispose method, but at

least you can be sure that it will be called, even if it’s only when the program shuts down. Here’s an example of how to do this:

class Example : IDisposable

{

...

~Example()

{

Dispose();

}

public virtual void Dispose()

{

if (!this.disposed)

{

try {

// release scarce resource here

}

finally {

this.disposed = true; GC.SuppressFinalize(this);

}

}

}

public void SomeBehavior() // example method

{

checkIfDisposed();

...

}

...

private void checkIfDisposed()

{

if (this.disposed)

{

throw new ObjectDisposedException(“Example: object has been disposed”);

}

}

private Resource scarce; private bool disposed = false;

}

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]