为什么通过值传递的对象被修改,好像它们是通过引用传递的?

时间:2012-08-15 22:02:50

标签: c#

例如,

  class Age
  {
    public int Year
    {
      get;
      set;
    }
    public Age(int year)
    {
      Year = year;
    }
  }

  class Person
  {
    public Age MyAge
    {
      get;
      set;
    }
    public Person(Age age)
    {
      age.Year = ( age.Year * 2 );
      MyAge = age;      
    }
  }

[客户]

Age a = new Age(10);
Person p = new Person( a );

当构造一个新的Age类时,Year属性为:10。但是,Person类将Year更改为20,即使没有ref关键字......

有人可以解释为什么年份不是10岁?

2 个答案:

答案 0 :(得分:2)

通过值传递对象的引用。使用该引用,可以修改对象实例本身。

请考虑以下示例以了解该陈述的含义:

public class A
{
    private MyClass my = new MyClass();

    public void Do()
    {
        TryToChangeInstance(my);
        DoChangeInstance(my);
        DoChangeProperty(my);
    }

    private void TryToChangeInstance(MyClass my)
    {
        // The copy of the reference is replaced with a new reference.
        // The instance assigned to my goes out of scope when the method exits.
        // The original instance is unaffected.
        my = new MyClass(); 
    }

    private void DoChangeInstance(ref MyClass my)
    {
        // A reference to the reference was passed in
        // The original instance is replaced by the new instance.
        my = new MyClass(); 
    }

    private void DoChangeProperty(MyClass my)
    {
        my.SomeProperty = 42; // This change survives the method exit.
    }
}

答案 1 :(得分:-1)

因为Age引用类型。