C# 语言特性系列(8) 深入理解String
在.NET中,string数据类型很特别,它本身是引用类型,这是毫无疑问的.但是有时它表现出让人困惑的行为!
Scenario1:
C#代码1:结果是True
1 namespace String
2 {
3 class Program
4 {
5 static void Main(string[] args)
6 {
7 string a = "fram";
8 string b = "fram";
9
10 Console.WriteLine(object.ReferenceEquals(a,b));
11 }
12 }
13 }
2 {
3 class Program
4 {
5 static void Main(string[] args)
6 {
7 string a = "fram";
8 string b = "fram";
9
10 Console.WriteLine(object.ReferenceEquals(a,b));
11 }
12 }
13 }
MSIL 代码1:
1 IL_0000: nop
2 IL_0001: ldstr "fram"
3 IL_0006: stloc.0
4 IL_0007: ldstr "fram"
5 IL_000c: stloc.1
6 IL_000d: newobj instance void String.One::.ctor()
7 IL_0012: stloc.2
8 IL_0013: ldloc.0
9 IL_0014: ldloc.1
2 IL_0001: ldstr "fram"
3 IL_0006: stloc.0
4 IL_0007: ldstr "fram"
5 IL_000c: stloc.1
6 IL_000d: newobj instance void String.One::.ctor()
7 IL_0012: stloc.2
8 IL_0013: ldloc.0
9 IL_0014: ldloc.1
Scenario2:
C#代码2:结果是False
1 namespace String
2 {
3 class Program
4 {
5 static void Main(string[] args)
6 {
7 string a = "hello123";
8 string b = "123";
9 string d = "hello" + b;
10
11 Console.WriteLine(object.ReferenceEquals(a,d));
12 }
13 }
14 }
2 {
3 class Program
4 {
5 static void Main(string[] args)
6 {
7 string a = "hello123";
8 string b = "123";
9 string d = "hello" + b;
10
11 Console.WriteLine(object.ReferenceEquals(a,d));
12 }
13 }
14 }
MSIL代码2:
1 IL_0000: nop
2 IL_0001: ldstr "hello123"
3 IL_0006: stloc.0
4 IL_0007: ldstr "123"
5 IL_000c: stloc.1
6 IL_000d: ldstr "hello"
7 IL_0012: ldloc.1
8 IL_0013: call string [mscorlib]System.String::Concat(string,
9 string)
2 IL_0001: ldstr "hello123"
3 IL_0006: stloc.0
4 IL_0007: ldstr "123"
5 IL_000c: stloc.1
6 IL_000d: ldstr "hello"
7 IL_0012: ldloc.1
8 IL_0013: call string [mscorlib]System.String::Concat(string,
9 string)