在 C# 中销毁对象
Muhammad Maisam Abbas
2023年10月12日

本教程将介绍销毁 C# 中的类对象的方法。
通过在 C# 中分配 null
值来销毁类对象
类对象是 C# 程序中的引用类型变量。这意味着它实质上是一个指针,该指针持有对类的存储位置的引用。不幸的是,在 C# 中没有破坏对象的事情。我们只能使用 C# 处置对象,这仅在类实现 IDisposable
的情况下才可行。对于任何其他类类型的对象,我们必须为该类对象分配一个 null
值。这意味着该对象不指向任何内存位置。类对象超出范围,垃圾收集器收集垃圾并重新分配内存。以下代码示例向我们展示了如何通过在 C# 中分配 null
值来销毁类对象。
using System;
namespace destroy_object {
class Sample {
public string Name { set; get; }
}
class Program {
static void Main(string[] args) {
Sample s = new Sample();
s.Name = "Sample name";
Console.WriteLine(s.Name);
s = null;
}
}
}
输出:
Sample name
在上面的代码中,我们用 C# 中的 s = null
破坏了 Sample
类的对象 s
。
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