gpt4 book ai didi

c# - 需要一些关于引用类型的说明

转载 作者:太空宇宙 更新时间:2023-11-03 21:33:47 25 4
gpt4 key购买 nike

所以我正在阅读 Jon Skeet 撰写的一篇关于在 C# 中传递参数的文章,他制作了以下示例来解释引用类型的工作原理,但我无法理解它。

StringBuilder first = new StringBuilder();
first.Append("hello");
StringBuilder second = first;
first.Append(" world");
first = new StringBuilder("goodbye");
Console.WriteLine(first); // Prints goodbye
Console.WriteLine(second); // Still prints hello world

当我们为 second 变量赋值时,我们只是将该值设置为 StringBuilder 对象的引用吗?

还有一个额外的问题,如果我们将 second 变量的引用更改为其他内容(例如将其设置为 null 值),那么对第一个 StringBuilder 的引用 对象将无法恢复?或者有什么方法可以检索特定类型的所有已创建对象?

最佳答案

When we're assigning the value of the second variable are we just setting that value to the reference of the StringBuilder object?

是的。我们只是复制一个指针到包含“hello world”的内存。

if we would change the reference of the second variable to something else, would the reference to the first StringBuilder object then be irretrievable? Or is there any way to retrieve all created objects of a certain type?

是的,由它分配的内存将成为垃圾回收的候选者,因为没有任何指针引用它。

关于c# - 需要一些关于引用类型的说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22907968/

25 4 0
文章推荐: c# - 使用保存到内存流的图像导出文件
文章推荐: c# - 将 List 绑定(bind)到 c# wpf 中的组合框