Home C# Class 02
Post
Cancel

C# Class 02

Shallow Copy/Deep Copy

클래스는 참조 형식이다. 참조 형식은 힙 영역에 객체를 할당하고 스택에 있는 참조가 힙 영역에 할당된 메모리를 가리킨다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    class MyClass
    {
        public int Field1;
        public int Field2;
    }

    MyClass Test1 = new MyClass();
    Test1.Field1 = 10;
    Test1.Field2 = 20;

    MyClass Test2 = Test1;
    Test2.Field2 = 30;

    Console.WriteLine("{0} {1}", Test1.Field1, Test1.Field2);   // 10 30
    Console.WriteLine("{0} {1}", Test2.Field1, Test2.Field2);   // 10 30

Test2는 Test1과 같은 메모리를 가리키게 되어 Test1의 Field2의 값이 30으로 바뀌게 된다. 이렇게 참조만 복사하는 것을 얉은 복사(Shallow Copy)라고 한다.

참조를 복사하는 것이 아니라 별도의 힙 공간을 할당해서 값을 복사하는 것을 깊은 복사(Deep Copy)라 하며, C#에서는 깊은 복사를 직접 코드로 만들어 사용한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    class MyClass
    {
        public int Field1;
        public int Field2;

        //Deep Copy
        public Myclass DeepCopy() {
            MyClass newCopy = new MyClass();
            newCopy.Field1 = this.MyField1;
            newCopy.Field2 = this.MyField2;
            return newCopy;
        }
    }

    MyClass Test1 = new MyClass();
    Test1.Field1 = 10;
    Test1.Field2 = 20;

    MyClass Test2 = Test1;
    Test2.Field2 = 30;

    Console.WriteLine("{0} {1}", Test1.Field1, Test1.Field2);   // 10 20
    Console.WriteLine("{0} {1}", Test2.Field1, Test2.Field2);   // 10 30

this

this는 객체가 자신을 지칭할 때 사용하는 키워드이다. 객체 내부에서는 자신의 필드나 메소드에 접근할 때 this를 사용한다.

1
2
3
4
5
6
7
8
9
10
11
    class User {
        private string Name;
        
        public void SetName(string Name) {
            this.Name = Name;
        }

        public void GetName() {
            return Name;
        }
    }

this()는 생성자를 오버로딩할 때 사용할 수 있다. this()는 자기 자신의 생성자를 가리키며, 생성자에서만 사용이 가능하다.

1
2
3
4
5
6
7
8
9
10
11
    class MyClass {
        int a, b, c;

        public MyClass() {
            this.a = 1;
        }

        public MyClass(int b) : this() {    // this()는 MyClass()를 가리킨다.
            this.b = b;
        }
    }
This post is licensed under CC BY 4.0 by the author.