[C#] 얕은 복사, 깊은 복사

0시0분·2022년 7월 30일
0

C#

목록 보기
3/9

얕은 복사 (Shallow Copy)

객체가 참조타입의 멤버(string, array, class, ...)를 가지고 있다면
참조값은 복사되지만 참조되는 개체는 복사되지 않음

public class Owner
{
    public string name;

    public Owner() {}
}

public class Cat
{   
    public string name;
    public int age;
    public Owner owner;

    public Cat() {}
    public Cat(string s, int i, string n) 
    {
        name = s;
        age =  i;
        owner  = new Owner();
        owner.name = n;
    }

    public void PrintInfo()
    {
        Console.WriteLine(String.Format("My name is {0}, age is {1}. Owner name is {2}", 
        	this.name, this.age, this.owner.name));
    }

    public Cat ShallowCopy()
    {
        return (Cat)this.MemberwiseClone();		// 🐣
    }
}

public class Execute
{
    static void Main(string[] args)
    {
        Cat cat1 = new Cat("blue", 2, "홍길동");
        cat1.PrintInfo();	// My name is blue, age is 2. Owner name is 홍길동

        Cat cat2 = cat1.ShallowCopy();
        cat2.name = "red";
        cat2.age = 4;
        cat2.owner.name = "김철수";

        cat1.PrintInfo();	// My name is blue, age is 2. Owner name is 김철수
        cat2.PrintInfo();	// My name is red, age is 4. Owner name is 김철수
    }
}

🐣 MemberwiseClone()
https://docs.microsoft.com/ko-kr/dotnet/api/system.object.memberwiseclone?view=net-6.0#system-object-memberwiseclone


깊은 복사 (Deep Copy)

public class Cat : ICloneable	// 🐶
{
	...
    
    public object Clone()
    {
        Cat tmp = new Cat();
        tmp.name = this.name;
        tmp.age = this.age;
        tmp.owner = new Owner();
        tmp.owner.name = this.owner.name;

        return tmp;
    }
}

고유한 힙 메모리를 부여받도록 새 객체 생성

static void Main(string[] args)
{
    Cat cat1 = new Cat("blue", 2, "홍길동");
    cat1.PrintInfo();	// My name is blue, age is 2. Owner name is 홍길동

    Cat cat2 = (Cat)cat1.Clone();
    cat2.name = "red";
    cat2.age = 4;
    cat2.owner.name = "김철수";

    cat1.PrintInfo();	// My name is blue, age is 2. Owner name is 홍길동
    cat2.PrintInfo();	// My name is red, age is 4. Owner name is 김철수
}

🐶 ICloneable
https://docs.microsoft.com/ko-kr/dotnet/api/system.icloneable?view=net-6.0

0개의 댓글