字符串是不可改变的,StringBuilder的是可变的是、字符串、StringBuilder

2023-09-02 20:47:40 作者:光線暗的刺眼

可以与任一实施例说明

相关讨论: http://stackoverflow.com/questions/21078/whats-the-best-string-concatenation-method-using-c

推荐答案

您不能编辑字符串值,该字符串对象的每个方法返回改变原来的一个新的字符串代替。 StringBuilder的另一方面可以改变它的内容(增加新的字符串例如)。

You cannot edit the value of a string, each method of the string object returns a new string instead of altering the original. StringBuilder on the other hand can alter it's content (adding new strings for example).

string original = "the brown fox jumped over the lazy dog";
string altered = original.Insert(original.IndexOf("fox"), "cat");
// altered = the brown cat jumped over the lazy dog

您不能改变原始字符串的内容,除非你创建一个新的字符串,或重新参考实例到另一个字符串对象。

You cannot change the content of the original string unless you create a new string, or re-reference the instance to another string object.