字符串在C#中没有变化时字符串的可变性?

如果字符串操作没有改变字符串的值,那么最终是否会创建新实例?例如;

string str="foo"; str+=""; 

我知道C#中string和stringbuilder的区别。

不,仅当字符串操作更改字符串变量中的值时,才会创建新实例。 它可以使用ObjectIDGenerator类来certificate。值得阅读这篇完整的文章进行certificate

 using System; using System.Text; using System.Runtime.Serialization; namespace StringVsStringBuilder { class Program { static void Main(string[] args) { ObjectIDGenerator idGenerator = new ObjectIDGenerator(); bool blStatus = new bool(); //blstatus indicate whether instance is new or not string str = "Fashion Fades,Style Remains Same"; Console.WriteLine("initial state"); Console.WriteLine("str = {0}",str); Console.WriteLine("instance id : {0}",idGenerator.GetId(str,out blStatus)); Console.WriteLine("this is new instance : {0}",blStatus); //a series of operations that won't change value of str str += ""; //try to replace character 'x' which is not present in str so no change str = str.Replace('x','Q'); //trim removes whitespaces from both ends so no change str = str.Trim(); str = str.Trim(); Console.WriteLine("\nfinal state"); Console.WriteLine("str = {0}", str); Console.WriteLine("instance id : {0}", idGenerator.GetId(str, out blStatus)); Console.WriteLine("this is new instance : {0}", blStatus); Console.ReadKey(); } } } 

在此处输入图像描述

不,不。 您可以使用object.ReferenceEquals()简单地测试它,如下所示:

  string s = "test"; string q = s; s += ""; bool eq1 = object.ReferenceEquals(s, q); //--> References are equal s += "1"; bool eq2 = object.ReferenceEquals(s, q); //--> References are not equal any more 

String.Concat(string,string),通常是编译器将字符串’addition’转换成的内容,检查其中一个参数是null还是空,并返回非NullOrEmpty参数。 因此,在您的示例中,它将简单地返回str,并且不会创建任何对象。

但实际上, 编译器可能会优化您的整个操作 ,注意到您只是连接一个空字符串。 一个更好的测试是两个值都是变量,一个恰好包含一个空字符串。