字符串是不可变的? [英] string is immutable ?
问题描述
string的含义是什么是不可变的,我读到了这个主题,我明白对该字符串的任何新操作都会创建一个新对象?对吧?
- -
如果它是正确的,下面的代码是什么意思?
what is the meaning of string is immutable , i read about this topic and i understand that any new operation on that string will create a new object ? Right ??
- -
So if it is right , what is the meaning by below code ?
string x="Hello";
x="good morning";
上面代码含义是什么?
是第一行的x而x是第二行是否相同?或者它们是两个不同的对象?
请我理解,所以感谢任何示例演示,谢谢
what the above code meaning ?
is x in the first line and x is the second line are the same ? or they are two different object ?
please i need to understand , so appreciate any demonstration with example , thanks
推荐答案
字符串是不可变的。
这意味着当您向此字符串添加内容或删除字符时,会创建一个新字符串。
现有的字符串值引用保留并且不会被销毁。 />
Strings are immutable.
This means that when you add something to this string or remove a character, a new string is created.
The existing string value reference remains and is not destroyed.
string a = "1";
string b = "2";
string a = a + b;
此代码在内存中创建一个名为12的新字符串并将其分配给a。 1仍然存在并将在适当时收集。
This code creates a new string in memory called "12" and assigns it to a. "1" still remains and will be collected as and when appropriate.
字符串是不可变的意味着您无法更改对象本身,但您可以更改课程参考
String is immutable means that you cannot change the object itself, but you can change the reference ofcourse
例如,
For example,
string x="Hello";
x+="good morning";
Console.WriteLine(x); // will print, Hello good morning
-KR
-KR
字符串本质上是不可变的意味着我们无法将值重新分配给同一个对象。
当我们将值重新分配给变量时,例如
string a =Hello;
a = Hello World;
在上面的示例中,首先是创建一个对象并分配Hello值。但是当重新分配时,它会在内存中保留a的引用并将其销毁并创建值为Hello world的新对象。
String is immutable in nature means we can't reassign the the value to the same object.
When we will reassign the value to a variable like
string a="Hello";
a="Hello World";
In the above example first it is creating a object and assigning the "Hello" value. But when reassigning then it keeps the reference of "a" in memory and destroy it and create new object with value "Hello world".
这篇关于字符串是不可变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!