【问题标题】:What happens to the original data if i set a variable to null? c#如果我将变量设置为 null,原始数据会怎样? C#
【发布时间】:2019-07-31 23:46:52
【问题描述】:

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

例如:

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?
    }

}

【问题讨论】:

  • 如果一个对象不再有任何对它的引用,它最终会被垃圾收集器清理掉。在那之前,它会留在记忆中。

标签: c# object variables memory null


【解决方案1】:

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

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

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

【讨论】:

  • 非常感谢!这就解释了! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-12
  • 2018-04-20
  • 2020-10-15
  • 2019-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多