c#System.Net.NetworkCredential

c# System.Net.NetworkCredential

System.Net.NetworkCredential 没有 Dispose 方法。正确处理使用此 class 创建的对象的最佳方法是什么?

詹姆斯NT

您可以在 try 的最后部分将对象引用设置为 null。

var myCredential = new NetworkCredential();

try
{
    //Do stuff here
}
finally
{
    myCredential = null;
}

但是,.NET 垃圾回收应该在您的对象引用超出范围时立即将其标记为要回收。

如果一个对象没有实现 IDisposable,那么在您使用完它后 "dispose" 的正确方法是让它超出范围。

IDisposable 旨在允许对象清理它可能持有的任何非托管资源。如果对象仅包含托管资源,则没有理由处置它;一切都会被垃圾收集器清理掉。

来自MSDN

The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.

Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.