别名示例,尝试了解此问题

时间:2013-10-30 12:37:51

标签: c# java aliasing

我尝试了解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

1 个答案:

答案 0 :(得分:2)

a2a3都是同一对象的引用¹。由于您有一个对象(以及两个对象),因此通过任何引用更改对象都会通过任何引用再次显示更改。


¹参考这里是Java术语,用于C / C ++中称为指针的内容。当您在这些语言中使用指针别名时,您的示例将显示相同的行为。