HerryDong 2019-04-21 08:44 采纳率: 0%
浏览 1381

想请教各位大牛关于C#中StringBuilder赋值的问题

最近看了一段StringBuilder的代码,突然有点搞不明白了,想请教一下各位大牛!
第一段代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string a = "张三";
            string b = a;
            b = null;
            Console.WriteLine(a);
        }
    }
}

这段代码很好理解,字符串不可变,b的修改不会影响a
第二段代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Person a = new Person();
            Person b = a;
            b.Name = "李四";
            Console.WriteLine(a.Name);
        }
    }

    class Person
    {
        public string Name { get; set; } = "张三";
    }
}

这个也很好理解,a和b指向托管堆中同一个地址,b的修改会影响到a
第三段代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            StringBuilder a = new StringBuilder();
            a.Append("张三");

            StringBuilder b = a;
            b.Append("李四");

            Console.WriteLine(a.ToString());
            Console.WriteLine(b.ToString());

            b = null;
            Console.WriteLine(a.ToString());  // 为什么这里还是输出"张三李四"
        }
    }
}

这段代码最后已经把b赋值为null了,为什么a还是输出“张三李四”?希望各位高手能够帮助小弟解答一下!

  • 写回答

1条回答 默认 最新

  • threenewbee 2019-04-21 11:37
    关注

    这个道理很简单
    new StringBuilder(); 托管堆里有了一个SB
    StringBuilder a = new StringBuilder();
    a 指向这个sb
    StringBuilder b = a;
    b也指向sb
    b = null;
    b不指向sb了
    那么a现在呢,它还是指向sb啊。b = null关它什么事。

    你可能认为 b = null 的意思是让b指向的sb消失了,其实sb没有消失,只是b不指向它而已

    评论

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥30 用arduino开发esp32控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿