0

例如,

  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 关键字...

有人可以解释为什么 Year 还不是 10 吗?

4

2 回答 2

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.
    }
}
于 2012-08-15T22:05:54.727 回答
-1

因为Age引用类型。

于 2012-08-15T22:06:44.067 回答