Skip to main content
 首页 » 编程设计

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

2024年02月13日20unruledboy

所以我正在阅读 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?

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