-
Notifications
You must be signed in to change notification settings - Fork 22
string 特殊的引用类型
L edited this page Feb 18, 2020
·
3 revisions
String类型直接继承自Object。
直接继承自Object的类型一定是引用类型,因为所有的值类型都继承自System.ValueType(System.ValueType却是一个引用类型)。
string是引用类型,但是其又具有值类型的一些特性。
string字符串之间的比较,比较的是“值”,而不是“引用地址”。(MS重写了==运算符所致)
String被分配在堆上,而不是栈上。
string str1 = "I am a number";
string str2 = str1;
Console.WriteLine("str1 = " + str1);//I am a number
Console.WriteLine("str2 = " + str2);//I am a number
str1 = "I am another number";
Console.WriteLine("after str1 changed... str1 = " + str1);//I am another number
Console.WriteLine("after str1 changed... str2 = " + str2);//I am a number
string str3 = "I am a number";
bool r = str2 == str3;
bool r2 = str2.Equals(str3);
bool r3 = Object.ReferenceEquals(str2, str3);
Console.WriteLine(r);//true
Console.WriteLine(r2);//true
Console.WriteLine(r3);//true