关于 string和StringBuilder的区别参考MSDN。本文用程序演示它们在内存中的区别,及其因此其行为不同。

 

//Demo  string memory model

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            string a = "1234";

            string b = a;//a,and b point to the same address

            Console.WriteLine(a);

            Console.WriteLine(b);

 

            a = "5678";

            Console.WriteLine(a);

            Console.WriteLine(b);//That b's value is not changed means string's value cann't be changed


            Console.ReadKey();
        } 
            
    }
}

output:

1234

1234

5678;change a's value,b's value is not changed

1234

 

//Demo StringBuilder's memory model

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
  
            StringBuilder a = new StringBuilder("1234");
            StringBuilder b = new StringBuilder();
            b = a;
            a.Clear();
            a.Append("5678");
            Console.WriteLine(a);
            Console.WriteLine(b);
            Console.ReadKey();
        }

        
    }
}

 

output:

5678

5678

相关文章:

  • 2021-12-21
  • 2022-12-23
  • 2021-11-20
  • 2021-11-27
  • 2021-09-18
  • 2021-10-10
  • 2022-12-23
猜你喜欢
  • 2021-09-16
  • 2021-07-11
  • 2022-01-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案