C#的对象赋值

时间:2023-03-09 09:17:52
C#的对象赋值
例如
Class A
{
      int x = 0;
      int y = 0;
}
public void test()
{
      A test1 = new A( );
      A test2 = new A( );
      test1.x = 1;
      test1.y = 2;
      test2.x = 3;
      test2.y = 4;
      test1 = test2;//此时test1.x = 3; test1.y = 4;test2.x = 3;test2.y = 4;
      test1.x = 5;
      test1.y = 6;//此时test1.x = 5; test1.y = 6;这是理所当然的!但是这时候test2.x = 5;test2.y =6;因为对象赋值的原理是内存地址的传递,当test1 = test2执行后test1使用的就是test2的内存地址,此时对test1进行任何操作test2都会随之变化
}
你如果用一个对象给另一个对象赋值的话   赋值后 两个对象共用一个内存地址 不论你改哪一个两个对象都会一起改变。