我尝试了解Aliasing
并遇到这个例子:
public class A
{
// Instance variable
private double _x;
// 3 constructors
public A(double x)
{
_x = x;
}
public A()
{
_x = 0;
}
public A(A a)
{
_x = a._x;
}
// methods
public double getX()
{
return _x;
}
public void setX(double x)
{
_x = x;
}
public String toString()
{
return "A:" + _x;
}
}
static void Main(string[] args)
{
A a1 = new A(7);
A a2 = new A(a1);
A a3 = a2;
Console.WriteLine("a1 = " + a1.toString());
Console.WriteLine("a2 = " + a2.toString());
Console.WriteLine("a3 = " + a3.toString());
a1.setX(10);
Console.WriteLine("after setting 10 to a1:");
Console.WriteLine("a1 = " + a1.toString());
Console.WriteLine("a2 = " + a2.toString());
Console.WriteLine("a3 = " + a3.toString());
a3.setX(5);
Console.WriteLine("after setting 5 to a3:");
Console.WriteLine("a1 = " + a1.toString());
Console.WriteLine("a2 = " + a2.toString());
Console.WriteLine("a3 = " + a3.toString());
Console.ReadLine();
}
第一个Console.WriteLine
和第一个SetX
是 clrea 但为什么之后a3.setX(5)
a2 也改变了?根据声明A a3 = a2
和 SetX 参考a3