对于C#中b=a的N种情况分析
2010-09-30 21:00:39 来源:WEB开发网让我们局部修改上面的代码:
UserInfo a = new UserInfo() { UserName = "Baobao", Age = 27 };
UserInfo b = a;
//a.UserName = "AndersLiu";
//a.Age = 30;
a = new UserInfo() { UserName = "AndersLiu", Age = 30 };
Console.WriteLine("b.UserName: " + b.UserName);
Console.WriteLine("b.Age: " + b.Age);
输出结果:
结论:对a重新进行实例化,导致a指向一个新的UserInfo实例的地址。而b仍然指向原先那个UserInfo实例的地址,所以b不会随着a的改变而改变。从此b和a是两个没有任何关系的变量。
再来看一下值类型:
UserInfo2 a = new UserInfo2() { UserName = "Baobao", Age = 27 };
UserInfo2 b = a;
a.UserName = "AndersLiu";
a.Age = 30;
Console.WriteLine("b.UserName: " + b.UserName);
Console.WriteLine("b.Age: " + b.Age);
输出结果:
更多精彩
赞助商链接