在 Java 中,字符串是不可变的。如果我们有一个字符串并对其进行更改,我们将获得由同一变量引用的新字符串:
String str = "abc";
str += "def"; // now str refers to another piece in the heap containing "abcdef"
// while "abc" is still somewhere in the heap until taken by GC
据说int 和 double 在 C# 中是不可变的。这是否意味着当我们拥有 int 并稍后对其进行更改时,我们将获得由同一变量“指向”的新 int?同样的东西,但有堆栈。
int i = 1;
i += 1; // same thing: in the stack there is value 2 to which variable
// i is attached, and somewhere in the stack there is value 1
那是对的吗?如果不是, int 以什么方式不可变?