Csharp/CSharp Tutorial/Class/IDisposable — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 12:16, 26 мая 2010
Complex IDisposable pattern
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Security.Cryptography;
class MyClass : IDisposable
{
private IntPtr myHandle = IntPtr.Zero;
~MyClass()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
IntPtr h = myHandle;
if (h != IntPtr.Zero)
{
h = IntPtr.Zero;
}
}
}
public class MainClass
{
public static void Main()
{
using (MyClass mc = new MyClass())
{
}
}
}
implementation of IDisposable
using System;
class MyClass: IDisposable
{
private bool Disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if(!this.Disposed)
{
if(disposing)
{
//free any managed resources
}
//free unmanaged resources
}
Disposed = true;
}
~MyClass()
{
Dispose(false);
}
}
Simple IDisposable pattern
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Security.Cryptography;
class MyClass : IDisposable
{
private Stream myStream = null;
public void Dispose()
{
Stream s = myStream;
if (s != null)
((IDisposable)s).Dispose();
}
}
public class MainClass
{
public static void Main()
{
using (MyClass mc = new MyClass())
{
}
}
}