zoukankan      html  css  js  c++  java
  • 代码演示C#中string和StingBuilder内存中的区别

    关于 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

  • 相关阅读:
    前端工程师们,这些干货让你开发效率加倍
    我的代码片段
    人生至少有一次为了自己的勇气而活
    美食篇之御桥小聚
    美食篇之好好对自己
    F
    Github 简明教程
    A
    完美字符串
    1222: FJ的字符串 [水题]
  • 原文地址:https://www.cnblogs.com/rr163/p/3977388.html
Copyright © 2011-2022 走看看