C#内存管理(五)

为什么是这样的结果呢?我们来看一下程序过程:

如果我们没传递Thing对象的引用,那么我们将得到相反的结果。

拷贝和不拷贝

首先我们查看值类型,请使用下面的类和结构体。我们拥有一个Dude类包含个Name元素和2个Shoe。我们还有一个CopyDude()方法去产生一个新的Dude对象。

public struct Shoe {
  public string Color;
}
public class Dude {
  public string Name;
  public Shoe RightShoe;
  public Shoe LeftShoe;
  public Dude CopyDude () {
    Dude newPerson = new Dude();
    newPerson.Name = Name;
    newPerson.LeftShoe = LeftShoe;
    newPerson.RightShoe = RightShoe;
    return newPerson;
  }
  public override string ToString () {
    return (Name + " : Dude!, I have a " + RightShoe.Color +
      " shoe on my right foot, and a " +
       LeftShoe.Color + " on my left foot.");
  }
}

Dude类是一个引用类型并且因为Shoe结构是类的一个成员,所以它们都被分配到堆中。

运行下面的程序:

public static void Main () {
  Class1 pgm = new Class1();
  Dude Bill = new Dude();
  Bill.Name = "Bill";
  Bill.LeftShoe = new Shoe();
  Bill.RightShoe = new Shoe();
  Bill.LeftShoe.Color = Bill.RightShoe.Color = "Blue";
  Dude Ted = Bill.CopyDude();
  Ted.Name = "Ted";
  Ted.LeftShoe.Color = Ted.RightShoe.Color = "Red";
  Console.WriteLine(Bill.ToString());
  Console.WriteLine(Ted.ToString());
}

我们将得到如下的输出:Bill : Dude!, I have a Blue shoe on my right foot, and a Blue on my left foot.Ted : Dude!, I have a Red shoe on my right foot, and a Red on my left foot.那么我们将Shoe声明为一个引用类型又会产生什么结果呢?

public class Shoe {
  public string Color;
}

再次运行main()函数, 我们得到的结果是:Bill : Dude!, I have a Red shoe on my right foot, and a Red on my left foot

你可能感兴趣的:(String,struct,C#,Class)