當結構體 Shoe 作為類 Dude 的字段時:
Dude 會完整複製 Shoe 數據,修改副本不影響原對象。Dude 僅複製引用,副本與原對象共享同一 Shoe 實例,修改會相互影響。
public struct Shoe { public string Color; }
public class Dude
{
public string Name;
public Shoe LeftShoe, RightShoe;
public Dude CopyDude()
{
return new Dude
{
Name = this.Name,
LeftShoe = this.LeftShoe, // 值拷貝
RightShoe = this.RightShoe
};
}
}
// 測試
Dude bill = new Dude { Name = "Bill", LeftShoe = new Shoe { Color = "Blue" }, RightShoe = new Shoe { Color = "Blue" } };
Dude ted = bill.CopyDude();
ted.Name = "Ted";
ted.LeftShoe.Color = ted.RightShoe.Color = "Red";
// 輸出:
// Bill : Blue / Blue
// Ted : Red / Red ← 互不影響
public class Shoe { public string Color; } // 改為 class
// 相同測試代碼
// 輸出:
// Bill : Red / Red ← 被意外修改!
// Ted : Red / Red
| 類型 | 賦值/傳參行為 | 內存分布 |
|---|---|---|
| 值類型 (struct) | 逐位拷貝數據 | 內聯在包含者內部(棧或堆) |
| 引用類型 (class) | 拷貝引用(指針) | 對象在堆,包含者存引用 |