C#immutable int

Geo*_*kov 15 c# int immutability

在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
Run Code Online (Sandbox Code Playgroud)

据说 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
Run Code Online (Sandbox Code Playgroud)

那是对的吗?如果没有,int以什么方式不可变?

Eri*_*ert 21

跟进Marc(完全可以接受)的答案:整数值是不可变的,但整数变量可能会有所不同.这就是为什么他们被称为"变量".

数值是不可变的:如果您的值为12,则无法将其设为奇数,无法将其绘制为蓝色,依此类推.如果你试图通过添加一个来使它变得奇怪,那么你最终得到一个不同的值,13.也许你将该值存储在过去包含12的变量中,但这不会改变12的任何属性. 12保持与以前完全相同.


Mar*_*ell 16

你没有改变(也不能改变)关于int的东西; 你已经分配了一个新的 int值(并丢弃了旧的值).因此它是不可改变的.

考虑一个更复杂的结构:

var x = new FooStruct(123);
x.Value = 456; // mutate
x.SomeMethodThatChangedInternalState(); // mutate

x = new FooStruct(456); // **not** a mutate; this is a *reassignment*
Run Code Online (Sandbox Code Playgroud)

但是,这里没有"指向".结构直接在堆栈上(在本例中):不涉及引用.