我们都知道,string类是一个reference type。看下面这段代码:
对于string类的困惑string s1 = "hello";
对于string类的困惑
string s2 = s1;
对于string类的困惑Console.WriteLine(s1);
对于string类的困惑Console.WriteLine(s2);
对于string类的困惑s1 
= "world";
对于string类的困惑Console.WriteLine(s1);
对于string类的困惑Console.WriteLine(s2);
按理来说,s1被赋予world之后,那么s2应该也是指向这段内存空间,输出world,但实际上不是这样。
代码输出为:
hello
hello
world
hello
C#高级编程中是这么解释的,s1被修改后,会重新分配一块内存,来指向新的s1。这是解释了为什么会有这个结果。但是,它没有解释,CLR为什么要这么特殊处理string类。难道,因为string类用的特别多,要符合大家的使用习惯?

看下面这段代码,class很明显也是一个reference,但是结果却和上面不同。
对于string类的困惑// 类的定义
Console.WriteLine(t2.ToString());

上述代码输出的,是我们期望的值:
10
10
20
20

相关文章:

  • 2021-08-31
  • 2021-06-05
  • 2021-08-03
  • 2021-08-22
  • 2021-07-20
  • 2021-08-26
  • 2022-01-11
猜你喜欢
  • 2022-02-25
  • 2021-05-14
  • 2022-02-21
  • 2022-12-23
  • 2021-10-20
  • 2021-05-06
  • 2022-12-23
相关资源
相似解决方案