在 C# 中删除对象
    
    Muhammad Maisam Abbas
    2024年2月16日
    
    Csharp
    Csharp Object
    
 
本教程将讨论在 C# 中删除用户定义类的对象的方法。
在 C# 中通过给它分配 null 值来删除一个用户定义的类对象
    
一个类对象是指向该类的内存位置的引用变量。我们可以通过为其分配 null 值来删除该对象。这意味着该对象当前不包含对任何内存位置的引用。请参见以下示例。
using System;
namespace delete_object {
  public class Sample {
    public string value { get; set; }
  }
  class Program {
    static void Main(string[] args) {
      Sample x = new Sample();
      x.value = "Some Value";
      x = null;
      Console.WriteLine(x.value);
    }
  }
}
输出:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
在上面的代码中,我们初始化了 Sample 类的对象 x,并将值分配给了 value 属性。然后,我们通过将 null 分配给 x 来删除对象,并打印 x.value 属性。它给我们一个例外,因为 x 没有指向任何内存位置。
另一种有益的方法是在删除对象之后调用垃圾回收器。下面的代码示例中说明了这种方法。
using System;
namespace delete_object {
  public class Sample {
    public string value { get; set; }
  }
  class Program {
    static void Main(string[] args) {
      Sample x = new Sample();
      x.value = "Some Value";
      x = null;
      GC.Collect();
      Console.WriteLine(x.value);
    }
  }
}
在上面的代码中,我们在 C# 中使用 GC.Collect() 方法将 null 值分配给 x 对象之后,调用了垃圾回收器。
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn