C#immutable int [英] C# immutable int

查看:112
本文介绍了C#immutable int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,字符串是不可变的。如果我们有一个字符串并对其进行更改,我们将获得由同一个变量引用的新字符串:

  String str =abc ; 
str + =def; // now str指的是堆中包含abcdef的另一块
//而abc仍然在堆中的某个地方,直到GC


据说 int和double在C#中是不可变的。这是否意味着当我们有int并且稍后更改它时,我们会得到同一个变量指向的新int?同样的事情,但有堆栈。

  int i = 1; 
i + = 1; //同样的事情:在堆栈中有值2连接变量
// i,堆栈中某处有值1

这是正确的吗?如果没有,以什么方式是int immutable?

解决方案

你没有改变(并且不能关于int的一些事情;您已分配 int值(并丢弃旧值)。因此它是不可变的。



考虑一个更复杂的结构:

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

x = new FooStruct(456); // **不**变异;这是*重新分配*

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


In Java strings are immutable. If we have a string and make changes to it, we get new string referenced by the same variable:

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

It's been said that int and double are immutable in C#. Does it mean that when we have int and later change it, we would get new int "pointed" by the same variable? Same thing but with stack.

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

Is that correct? If not, in what way is int immutable?

解决方案

You haven't changed (and cannot change) something about the int; you have assigned a new int value (and discarded the old value). Thus it is immutable.

Consider a more complex struct:

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

x = new FooStruct(456); // **not** a mutate; this is a *reassignment*

However, there is no "pointing" here. The struct is directly on the stack (in this case): no references involved.

这篇关于C#immutable int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆