본문 바로가기

C#

객체 복사: 얕은 복사와 깊은 복사

얕은 복사

 class Program
    {
        static void Main(string[] args)
        {
            NewClass source = new NewClass();
            source.a = 10;
            source.b = 20;

            NewClass target = source;
            target.b = 30;

            Console.WriteLine($"{source.a} , {source.b}");      // 10, 30
            Console.WriteLine($"{target.a} , {target.b}");      // 10, 30
        }
    }

    class NewClass
    {
        public int a;
        public int b;
    }

 

source를 복사해서 받은 target은 힙에 있는 실제 객체가 아닌 스택에 있는 참조를 복사해서 받는다.

그래서 target을 바꿔도 source가 바뀌는 것이다.

이렇게 객체를 복사할 때 참조만 살짝 복사하는 것을 얕은 복사 Shallow Copy 라고 한다.

 

그렇다면 어떻게 다음 그림과 같이 target이 힙에 보관되어 있는 내용을 source로부터 복사해 별도의 힙 공간에 객체를 보관할 수 있을까?(깊은 복사: Deep Copy)

 

class Program
    {
        static void Main(string[] args)
        {
            NewClass source = new NewClass();
            source.a = 10;
            source.b = 20;

            NewClass target = source.DeepCopy();
            Console.WriteLine($"{source.a}, {source.b}");
            Console.WriteLine($"{target.a}, {target.b}");

            target.a = 60;
            Console.WriteLine($"{source.a}, {source.b}");
            Console.WriteLine($"{target.a}, {target.b}");
        }
    }

    class NewClass
    {
        public int a;
        public int b;

        public NewClass DeepCopy()
        {
            NewClass newCopy = new NewClass();
            newCopy.a = this.a;
            newCopy.b = this.b;

            return newCopy;
        }
    }

참조: 이것이 C#이다.

'C#' 카테고리의 다른 글

접근지정자  (0) 2022.05.12
생성자 오버로딩 / this()  (0) 2022.05.12
정적 필드와 메소드  (0) 2022.05.12
생성자  (0) 2022.05.12
객체지향 프로그래밍과 클래스  (0) 2022.05.09