代码之家  ›  专栏  ›  技术社区  ›  Jiew Meng

关于C#字符串的问题:不变性与克隆

c#
  •  2
  • Jiew Meng  · 技术社区  · 15 年前

    问题1

    一旦你创造了它们, 你不能改变它们

    这是怎么回事。我已经有一段时间没用C了,加上我才刚刚开始,所以我可能在语法上也错了。

    string str1 = "this is a string"; // i hope my syntax is right 
    str1 = "this is a NEW string"; // i think i can do this right? 
    

    指向同一个 字符串数据作为源。事实上, ICloneable.Clone 只返回一个 引用此

    string str1 = "string 1";
    // i hope my syntax is right too. i am really not sure about this
    string str2 = str1.Clone(); 
    str2 = "modified string"; // will str1 be modified too? 
    
    4 回复  |  直到 15 年前
        1
  •  13
  •   Heinzi    15 年前
    string str1 = "this is a string"; // i hope my syntax is right 
    str1 = "this is a NEW string"; // i think i can do this right? 
    

    string 是引用类型(a 指针 ,如果您想这样看),那么在第2行中,您将 str1 指向 (常量)内存中的字符串。原始字符串没有改变,只是不再被引用。

    string str1 = "string 1";
    string str2 = str1.Clone(); // i hope my syntax is right too. i am really not sure about this
    str2 = "modified string"; // will str1 be modified too? 
    

    不,因为你没有修改 "string 1" . 在2号线之后,它看起来是这样的:

    memory            "string 1"
                        ^    ^ 
                        |    |
    stack             str1  str2
    

    memory            "string 1"     "modified string"
                          ^              ^
                          |              |
    stack                str1           str2
    
        2
  •  2
  •   ravibhagw    15 年前

    这里一致的答案是正确的。

    字符串类型是内存中不可变字符串的引用类型。所有字符串的集合将在内存中创建(恰当地称为字符串池),其中包含已创建的字符串。在问题1中,第一个语句在内存中创建一个字符串,并在字符串池中为str1分配一个对该字符串的引用。

    当您执行以下操作时

    str1 = "this is a NEW string";
    

    实际上,您正在向字符串池添加一个新字符串(透明地创建一个新字符串),然后为str1分配一个对新字符串的引用。

    例如,考虑一下:

    string str1 = "this is my old string";
    str1 = "this is my NEW string"; 
    str1 = "this is my old string";
    

    在这个场景中,在字符串池中只创建两个字符串。当您到达代码中的第三行时,.NET平台将检查字符串池,找到匹配项,并向str1提供对字符串池中已存在的字符串的引用,而不是创建重复的字符串。

    string str1 = "this is a string";
    string str2 = "this is a string";
    //both strings have a reference to the same string in memory
    str1 = str1.Replace("this","xxxx");
    

    字符串是不可变的,因为一旦它们存在 在记忆中 ,不能更改。C中的StringBuilder允许我们避免这个问题。我们可以自由地修改StringBuilder对象中的内容。在调用.ToString()方法之前,我们创建的字符串不会提交到字符串池。

        3
  •  1
  •   Steven Sudit    15 年前

    你指的是 .

    这就是为什么可以更改字符串变量赋值。

    不可能,但出于所有的意图和目的,应该被认为是这样)。

    新的 串;调用该方法的原始方法是不可变的。

        4
  •  0
  •   NickHalden    15 年前

    正确,如果这不是所需的功能,请查看StringBuilder对象。

    问题2: