立项和启动的区别:C#中如何销毁一个对象?

来源:百度文库 编辑:查人人中国名人网 时间:2024/04/28 12:32:51
用new方法新建一个对象,然后处理完成后需要显示地销毁这个对象,怎么操作?

给他赋值Null就可以了。然后系统会自动清理内存的。
直接用这个 GC.Collect()会清理无用内存,但是这样用性能不好,让系统自己调用最好。
A type that implements System.IDisposable declares fields that are of types that also implement IDisposable. The Dispose method of the field is not called by the Dispose method of the declaring type.

public class TypeA : IDisposable
{
// Assume this type has some unmanaged resources.
private bool disposed = false;

protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
// Dispose of resources held by this instance.
// (This process is not shown here.)

// Set the sentinel.
disposed = true;

// Suppress finalization of this disposed instance.
if (disposing)
{
GC.SuppressFinalize(this);
}
}
}

public void Dispose()
{
Dispose(true);
}

// Disposable types implement a finalizer.
~TypeA()
{
Dispose(false);
}
}

A type that implements System.IDisposable declares fields that are of types that also implement IDisposable. The Dispose method of the field is not called by the Dispose method of the declaring type.

public class TypeA : IDisposable
{
// Assume this type has some unmanaged resources.
private bool disposed = false;

protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
// Dispose of resources held by this instance.
// (This process is not shown here.)

// Set the sentinel.
disposed = true;

// Suppress finalization of this disposed instance.
if (disposing)
{
GC.SuppressFinalize(this);
}
}
}

public void Dispose()
{
Dispose(true);
}

// Disposable types implement a finalizer.
~TypeA()
{
Dispose(false);
}
}