对象间引用赋值及方法时引用传递
考虑下面代码:
class Program { static void Main(string[] args) { C c1 = new C(); c1.str = "hello"; C c2 = new C(); c2 = c1; //对象名即是对象引用,对象间赋值即是引用复制赋值,此时栈区的c2和c1同时指向堆区的同一块内存区域 Console.WriteLine(c1.str); Console.WriteLine(c2.str); c2.str = "world"; Console.WriteLine(c1.str); Console.WriteLine(c2.str); Set(c1,"test1"); Console.WriteLine(c1.str); Console.WriteLine(c2.str); Set(c2, "test2"); Console.WriteLine(c1.str); Console.WriteLine(c2.str); Console.ReadKey(); } //对象名作为参数传入时,传入的是对象的引用 public static void Set(C c,string msg) { c.str = msg; } } class C { public string str = string.Empty; }
体会输出结果: