Class資料複製 (ShallowCopy)(淺層複製)
void Main()
{
ClassData a = new ClassData() { Class_1="11", Class_2="22" };
ClassData b = a.ShallowCopy(); //淺層複製(Shallow Copy) 複製值
ClassData c = a; //複製參考
a.Class_1="AA";
string result_B = $"B.Class_1='{b.Class_1}'"; //-->11
string result_C = $"C.Class_1='{c.Class_1}'"; //-->AA
result_B.Dump();
result_C.Dump();
}
class ClassData
{
public string Class_1 { get; set; }
public string Class_2 { get; set; }
public ClassData ShallowCopy()
{
return (ClassData)this.MemberwiseClone(); //複製值, 而非reference
}
}
顯示結果:
B.Class_1='11'
C.Class_1='AA'
留言
張貼留言