这会导致旧字符串对象被垃圾回收还是它仍然是对同一对象的相同引用?
string str = "Hello World!";
str = str.ToUpper();
我了解 GC 的作用及其不可预测性。
最佳答案
Does this cause the old string object to be garbage collected
我们不能说。有两个原因:
- 我们不知道是否还有对该字符串的其他引用。如果有对该字符串的其他引用,则该字符串将不符合收集条件。注意:如果您显示的代码是完整代码,则不会有其他引用。
- 即使字符串符合垃圾收集条件,也无法知道垃圾收集器何时运行。我们甚至不知道垃圾收集器是否会运行。
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/