객체 복사할 때 참조만 복사하는 것은 얕은 복사(ShallowCopy)
예시 코드
//----Class1.cs----//
using System;
namespace ConsoleApp1202
{
class MyClass
{
public int MyField1;
public int MyField2;
}
}
//----Program.cs----//
using System;
using static System.Console;
namespace ConsoleApp1202
{
public class Program
{
static void Main(string[] args)
{
MyClass source = new MyClass();
source.MyField1 = 10;
source.MyField2 = 20;
MyClass target = source; // ShallowCopy, 참조만 복사함
target.MyField2 = 30;
System.Console.WriteLine("{0} {1}", source.MyField1, source.MyField2); // 10 30
System.Console.WriteLine("{0} {1}", target.MyField1, target.MyField2); // 10 30
}
}
}
깊은 복사(DeepCopy)는 힙에 보관되어 있는 내용을 source로부터 복사해서 받아 별도의 힙 공간에 객체를 보관하는 것
예시 코드
using System;
namespace DeepCopy
{
class MyClass
{
public int MyField1;
public int MyField2;
public MyClass DeepCopy()
{
MyClass newCopy = new MyClass();
newCopy.MyField1 = this.MyField1;
newCopy.MyField2 = this.MyField2;
return newCopy;
}
}
class MainApp
{
static void Main(string[] args)
{
Console.WriteLine("Shallow Copy");
{
MyClass source = new MyClass();
source.MyField1 = 10;
source.MyField2 = 20;
MyClass target = source; // ShallowCopy
target.MyField2 = 30;
Console.WriteLine($"{source.MyField1} {source.MyField2}"); // 10 30
Console.WriteLine($"{target.MyField1} {target.MyField2}"); // 10 30
}
Console.WriteLine("Deep Copy");
{
MyClass source = new MyClass();
source.MyField1 = 10;
source.MyField2 = 20;
MyClass target = source.DeepCopy(); // DeepCopy
target.MyField2 = 30;
Console.WriteLine($"{source.MyField1} {source.MyField2}"); // 10 20
Console.WriteLine($"{target.MyField1} {target.MyField2}"); // 10 30
}
}
}
}
class Employee
{
private string Name; // Employee 클래스의 필드도 Name이고
private string Position;
public void SetName(string Name) // SetName 메소드의 매개변수도 Name이므로
{
this.Name = Name; // 자신의 필드에 this 붙여서 구별
}
}