c# - 在调用 ToUpper() 等之后,旧字符串对象是否会被垃圾回收?

标签 c# garbage-collection

这会导致旧字符串对象被垃圾回收还是它仍然是对同一对象的相同引用?

    string str = "Hello World!"; 
    str = str.ToUpper();

我了解 GC 的作用及其不可预测性。

最佳答案

Does this cause the old string object to be garbage collected

我们不能说。有两个原因:

  1. 我们不知道是否还有对该字符串的其他引用。如果有对该字符串的其他引用,则该字符串将不符合收集条件。注意:如果您显示的代码是完整代码,则不会有其他引用。
  2. 即使字符串符合垃圾收集条件,也无法知道垃圾收集器何时运行。我们甚至不知道垃圾收集器是否会运行。

or is it still the same reference to the same object?

没有。您创建了一个新字符串。 The documentation 清楚地声明(大胆强调我的):

Returns a copy of this string converted to uppercase.

Note: This method does not modify the value of the current instance. Instead, it returns a new string in which all characters in the current instance are converted to uppercase.

此外,string 是不可变的,因此无论如何都不能更改。

关于c# - 在调用 ToUpper() 等之后,旧字符串对象是否会被垃圾回收?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49591811/

相关文章:

c# - 无法从 .NET 4.6 中的 C# Web 项目引用 F# 库?

javascript - 内存处理与性能

c# - 为什么 C# 垃圾收集行为对于 Release 和 Debug 可执行文件不同?

java - Java 和 PHP 应用程序的 GC 和内存行为?

c# - 现有项目中的 ASP.net MVC 5 区域无法正常工作

c# - Process.Start() 在 Windows 10/Chrome 上去掉井号和之后的所有内容

Java 垃圾回收和大对象

c++ - 垃圾收集器 : data structure of the object graph

c# - 在 ASP .NET CORE 中更新 Web 应用程序替换文件或删除文件,更新时如何在应用程序中保留文件

C# 实用功能静态方法/静态类/单例模式