在C#中,可变字符串和不可变字符串有什么区别?
数据值可能无法更改。注意:变量值可以更改,但原始不可变数据值已被丢弃,并在内存中创建了一个新的数据值。
来自http://yassershaikh.com/what-is-the-difference-between-strings-and-stringbuilder-in-c-net/
简短回答:String是不可变的,而StringBuilder是可变的。
这是什么意思? 维基百科说:在面向对象编程中,不可变对象是指其状态在创建后无法修改的对象。这与可变对象形成对比,可变对象在创建后可以被修改。
从StringBuilder类文档中得知:
String对象是不可变的。每次使用System.String类中的方法时,都会在内存中创建一个新的字符串对象,这需要为该新对象分配新的空间。
在需要对字符串执行重复修改的情况下,创建新的String对象所需的开销可能很大。
当您想要修改字符串而不创建新对象时,可以使用System.Text.StringBuilder类。例如,在循环中连接许多字符串时,使用StringBuilder类可以提高性能。
使用StringBuilder来连接大量数据字符串是更好的选择,因为StringBuilder是可变字符串类型,而StringBuilder对象是不可变类型,这意味着在连接字符串时,StringBuilder永远不会创建新的对象实例。
如果我们使用字符串而不是StringBuilder来实现连接,则每次都会在内存中创建新的实例。
C# 中的字符串是不可变的。如果你将其与任何字符串连接起来,实际上是在创建一个新的字符串对象!但 StringBuilder 可以创建可变字符串。
这里是不可变字符串和可变字符串构建器的示例
Console.WriteLine("Mutable String Builder");
Console.WriteLine("....................................");
Console.WriteLine();
StringBuilder sb = new StringBuilder("Very Good Morning");
Console.WriteLine(sb.ToString());
sb.Remove(0, 5);
Console.WriteLine(sb.ToString());
Console.WriteLine();
Console.WriteLine("Immutable String");
Console.WriteLine("....................................");
Console.WriteLine();
string s = "Very Good Morning";
Console.WriteLine(s);
s.Substring(0, 5);
Console.WriteLine(s);
Console.ReadLine();