【问题标题】:Examples to understand string immutablility in c# [duplicate]了解 C# 中字符串不变性的示例 [重复]
【发布时间】:2014-11-09 06:41:39
【问题描述】:

“字符串在 c# 中是不可变的”是什么意思。我需要一些例子来理解这一点。我找不到一些合适的例子来理解这一点

【问题讨论】:

  • 每次更改字符串时,都会生成一个新字符串。您不能更改现有字符串,因此是不可变的。
  • string s = "bob"; s[2] = 'a' 是不允许的。您不能更改字符串。这就是“不变性”的含义。
  • @PeteGarafano 不变性的全部意义在于您不能更改字符串。并不是说你可以改变一个字符串然后创建一个新字符串。
  • @Servy 其措辞语义。在幕后,字符串永远不会改变,“改变”字符串的操作会导致返回一个全新的字符串对象。为简单起见,它是一个“新”字符串。

标签: c#


【解决方案1】:

搜索您的文本“字符串在 c# 中是不可变的”我发现:http://msdn.microsoft.com/en-us/library/362314fe.aspx

这似乎是在说字符串永远不会改变对象,它们总是被销毁并重新创建。

每个微软:

Strings are immutable--the contents of a string object cannot be changed after the 
object is created, although the syntax makes it appear as if you can do this. 
For example, when you write this code, the compiler actually creates a new string object 
to hold the new sequence of characters, and that new object is assigned to b. The string "h" 
is then eligible for garbage collection.

string b = "h";
b += "ello";

【讨论】:

    【解决方案2】:

    这意味着如果你分配

    string s = "Hello";
    

    你不能修改字符串 s。因此,如果你这样做

    s = "Goodbye";
    

    文字“Hello”没有被修改,但新的文字“Goodbye”被分配给s。

    【讨论】:

      猜你喜欢
      • 2016-12-01
      • 2013-09-18
      • 2019-06-07
      • 2013-05-19
      • 2015-04-15
      • 2011-04-05
      • 1970-01-01
      • 2015-02-23
      相关资源
      最近更新 更多