我是C#的初学者,我不知道为什么这不起作用,我只想通过调用Dispose()方法将此对象设置为null .
为什么这不可能?
class MyClass:IDisposable
{
public void Dispose()
{
this = null;
}
}
Run Code Online (Sandbox Code Playgroud)
所述的目的Dispose的方法没有清理那个类,但清理这个类保持到一次性依赖性,以便它可以被垃圾收集器被设置的正常进行.
我建议阅读更多有关Dispose模式以及如何在C#中实现它的内容.
一点迂腐:这个Dispose方法不是析构函数,也不是终结者.
您的问题似乎真的是"如何删除C#中的内容".简短的回答是你不能,这是垃圾收集器的工作System.GC.该IDisposableinerface用于确保项重要的资源不属于净(如文件或网络/数据库连接,但不是一个.NET类),是按需清理.
该IDisposable接口是非常重要的,因为它允许你使用using模式.也就是说,如果您的类实现IDisposable它可以在using块中使用.考虑例如:
class MyClass : IDisposable {
public void Dispose() { }
}
Run Code Online (Sandbox Code Playgroud)
这个类现在可以像这样使用:
using (MyClass instance = new MyClass())
{
} // instance.Dispose() is called here at the end of the block.
Run Code Online (Sandbox Code Playgroud)
使用块的意思是当块结束时,编译器将抛出一个调用Dispose(),您可以使用它来删除文件和数据库连接等重要资源.例如,所有Stream类,类似FileStream和未实现的类,IDisposable因为保持文件打开是个坏主意.相反,您将所有访问权限包含在一个using块中,然后保证FileStream.Dispose将关闭该文件.考虑:
using (FileStream myFile = File.OpenRead("..."))
{
// Read the content of the file.
} // The file is guaranteed to be closed here. Cool!
Run Code Online (Sandbox Code Playgroud)
这比做这样的事情要简洁得多:
FileStream stream = File.OpenRead(" ... ");
stream.Close(); // Yes, you closed it manually, but it's error prone. What if you forget to do this?
Run Code Online (Sandbox Code Playgroud)
现在你所想的是一个名为"终结"的术语,即实际销毁这个类的时候.当垃圾收集器(System.GC类)实际销毁对象并清理其内存时,就会发生这种情况.考虑:
public class MyClass {
// This method, the 'Finalizer' will be called when the class is destroyed.
// The 'finalizer' is essentially just the name of the class with a '~' in front.
~MyClass() {
Console.WriteLine("Destroyed!");
}
}
public class Program {
public static void Main() {
MyClass referenceHeld = new MyClass(); // Reference held
new MyClass(); // No reference held on this class
WeakReference sameAsNoReference = new WeakReference(new MyClass()); // Equivalent to no reference.
System.GC.Collect(); // Force the garbage collector to collect
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
简而言之,垃圾收集器是运行时的一部分,用于清除未使用的内容.不使用是什么意思?这意味着没有附加到对象的引用.例如,如果您运行上面的程序,您会注意到"Destroyed"一词会在屏幕上打印两次.那是因为函数中MyClass创建的两个实例Main没有通过引用指向(A WeakReference与没有引用基本相同).当我们调用GC.Collect()垃圾收集器运行并清理引用时.
这就是说,你应该不叫GC.Collect你自己.当然,你可以进行实验和教育,但是大多数人会告诉你,垃圾收集器可以很好地保持自己的清洁.GC.Collect在你的代码中散布一堆是没有意义的,因为这就是拥有垃圾收集器的重点 - 不必担心自己清理事物.
所以简而言之,除非你打电话GC.Collect()(你不应该这样做),否则你真的无法自己销毁物品.该IDisposable界面允许您使用using模式,确保释放重要资源(这与销毁对象不同!所有IDisposable确实是确保Dispose()在using块退出时调用,以便您可以清理重要的东西,但是对象仍然存在 - 一个重要的区别).