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 になります。ただし、ref キーワードがなくても、Person クラスは Year を 20 に変更します...

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 に答える