如果我将变量设置为空,原始数据会发生什么?C#

Tom*_*mmy 1 c# memory variables null object

我只是想知道如果我将其分配的变量设置为空,原始数据会发生什么?

例如:

class Fruits{
    public int Count;
    public List<string> Names;
}

class Main{
    private Fruits fruits = new fruits();

    void SetFruitsToNull(){
        this.fruits = null;//What happens to the original fruits variable's value? Does it get deleted?
    }

}
Run Code Online (Sandbox Code Playgroud)

Chr*_*her 5

您的精确示例中的变量不再被引用,因此可以由垃圾收集器收集。我可以向你保证它会运行 - 即使出现异常 - 但不会在它运行时运行。对于大多数情况,这不是问题。

如果您已经将引用复制到另一个变量,则它不再在“fruits”下被引用 - 但仍然在您分配给它的任何其他变量下。如果仍然存在对该实例的强引用,则 GC 无法工作

如果您有一些未修改的资源需要及时释放(任何网络或文件句柄),这就是 IDisposeable 模式和使用块的用途。