2020年11月7日 星期六

MemberwiseClone

https://dotblogs.com.tw/stanley14/2017/03/28/Shallow_And_Deep_Copy

先在測試專案中新增測試用的類別(Class)並且新增淺層複製(Shallow Copy)的方法

public class Person
{
    public IdInfo IdInfo;
    public int Age { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public List<string> Phones { get; set; } = new List<string>();

    public Person ShallowCopy()
    {
        return (Person)this.MemberwiseClone();
    }
}
public class IdInfo
{
    public int IdNumber;
    public IdInfo(int IdNumber)
    {
        this.IdNumber = IdNumber;
    } 

} 


實驗原始物件值被覆蓋(指派)

輸入以下程式碼,尤其是以下這兩行屬性值的修改

    p2.Phones.Clear();
    p2.IdInfo.IdNumber = 17;
public void TestShallowCopyReplace2()
{
    var p1 = new Person
    {
        Name = "長澤雅美",
        Age = 30,
        Address = "日本静岡縣磐田市",
        Phones = new List<string> { "9", "1", "1" },
        IdInfo = new IdInfo(1)
    };

    var p2 = p1.ShallowCopy() as Person;
    p2.Name = "史丹利";
    p2.Age = 36;
    p2.Address = "台灣台北市內湖區";
    p2.Phones.Clear();
    p2.IdInfo.IdNumber = 17;

    Console.WriteLine($"person1 Name={p1.Name},Age={p1.Age},Address={p1.Address},phone={p1.Phones.Count},id={p1.IdInfo.IdNumber}");
    Console.WriteLine($"person2 Name={p2.Name},Age={p2.Age},Address={p2.Address},phone={p2.Phones.Count},id={p2.IdInfo.IdNumber}");
}

執行結果:

電話和ID兩個屬性果然被覆蓋了!

重新看一下MemberwiseClone的說明

 If a field is a value type, a bit-by-bit copy of the field is performed.   If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.  

如果欄位是實值型別,則會複製出欄位的複本。 如果欄位是參考型別,將只會複製參考!

沒有留言:

張貼留言