- 典型引用类型与值类型的例子:
class Program { static void Main(string[] args) { Patient patientOne = new Patient(); Patient PatientSecond = patientOne; patientOne.x = 10; patientOne.y = 20; Console.WriteLine("struct patientOne.x,patientOne.y分别为{0},{1}", patientOne.x, patientOne.y); //结果为10,20 Console.WriteLine("struct patientSecond.x,patientSecond.y分别为{0},{1}", PatientSecond.x, PatientSecond.y); //结果为0,0 因为是值类型,赋值时通过复制拷贝一份值的方式传值,传值完后,其中一方的修改与另一方无关 Person p1 = new Person(); Person p2 = p1; p1.x = 10; p1.y = 20; Console.WriteLine("class p1.x,p1.y分别为{0},{1}", p1.x, p1.y); Console.WriteLine("calss p2.x,p2.y分别为{0},{1}", p2.x, p2.y); //结果都是10,20,因为是引用类型,赋值时通过复制引用即指向堆中的内存地址,二者指向同一内存,可理解为共享数据. Console.ReadKey(); } } struct Patient { public int x; public int y; } class Person { public int x; public int y; }
图解:
- 引用类型参数与值类型参数的差别
class Program { static void Main(string[] args) { Patient patientOne = new Patient(); patientOne.life = "我生病了"; SeeDoctor(patientOne); Console.WriteLine("struct类型的patientOne的状态为:{0}",patientOne.life); Person person = new Person(); person.life = "我生病了"; SeeDoctor(person); Console.WriteLine("class类型的person的状态为:{0}", person.life); Console.ReadKey(); string s = "123"; string s1 = "123"; } public static void SeeDoctor(Patient p) { p.life = "我的病好了"; } public static void SeeDoctor(Person p) { p.life = "我的病好了"; } } struct Patient { public string life; } class Person { public string life; }
(注明:patientOne变量是在Main方法的线程栈上,p变量是在SeeDoctor方法的线程栈上)
例二的结构体图解:
说明:
例二中的类图解:
说明:
- 引用类型string的拘留池
class Program { static void Main(string[] args) { string s = "123"; string s1 = "123";//通过调试发现,s和s1指向同一内存拘留池 //.netFramework做的优化,字符串相同,一般对应的变量指向同一内存. char[] chs = new char[] { 'a', 'b', 'c', 'd' }; string s2 = new string(chs); string s3 = new string(chs);//通过调试发现.s2和s3没有指向同一内存 string kong = ""; string nul = null;//通过调试发现kong指向一个内存,而nul指向的内存地址为0x0000即没有分配内存 } }
通过调试,发现以上代码中各变量的内存地址为:
老师说代码:string str="";.最好的写法为string str=string.empty;.但是我调试后发现:
static void Main(string[] args) { string a= ""; string b = ""; string c = string.Empty; string d = string.Empty; }
四个变量都指向同一内存地址,不知道为什么老师说,string str=string.empty写法可以优化内存?