為什麼是這樣的結果呢?我們來看一下程序過程:
如果我們沒傳遞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