.NET中的字符串(4):字符串 - 特殊的引用类型

mac2022-06-30  27

字符串驻留

看一下这段代码:

 

1using System; 2 3namespace Demo4 4{ 5 /** <summary> 6 /// String的驻留 7 /// </summary> 8 public class Test 9 { 10 public static void Main(string[] args) 11 { 12 string a = "1234"; 13 string s = "123"; 14 s += "4"; 15 16 string b = s; 17 string c = String.Intern(s); 18 19 Console.WriteLine((object)a == (object)b); 20 Console.WriteLine((object)a == (object)c); 21 Console.ReadLine(); 22 } 23 } 24} 25

 

执行的结果:

False

True在这段代码中,比较这两个对象发现它的引用并不是一样的。如果要想是它们的引用相同,可以用Intern()函数来进行字符串的驻留(如果有这样的值存在)。

转载于:https://www.cnblogs.com/hoosway/p/3600598.html

最新回复(0)