[C# 문법] C# 클래스 객체 깊은복사(DeepClone) 하는 방법

안녕하세요.

 

오늘은 C# 문법에서 클래스 객체 복사하는 방법에 대해서 알려 드리려고 합니다.

 

그 중에서도, 깊은 복사를 하는 방법에 대해서 알려 드리려고 해요. 제가 최근에 프로젝트를 진행하면서 깊은복사, 얕은복사로 인해서 꽤 고생을 했던 경험이 있어서..

 

전역으로 다루는 클래스 객체가 있었는데, 해당 객체 안에 있는 List의 값을 변화 시키니까 모든 객체에서 객체 변화가 생기면서..데이터가 꼬이는 현상이 있었습니다.

 

원인은..해당 객체를 깊은복사를 해야 했는데..얕은복사로 객체를 복사해서 생기는 일이었습니다.

 

그래서 오늘은 C#에서 깊은 복사를 하는 방법에 대해서 소스코드로 알려 드리려고 합니다.

 

바로 예제 코드를 통해서 보여 드리도록 하겠습니다.

예제 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
 
namespace ConsoleApp6
{
    class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student()
            {
                Name = "범범조조",
                Age = "29",
                Grade = "A"
            };
 
            Student stu2 = DeepClone<Student>(stu);
            stu2.Name = "범범조조2";
 
            Console.WriteLine("stu2 객체");
            Console.WriteLine($"Name = {stu2.Name}, Age = {stu2.Age}, Grade = {stu2.Grade}");
            Console.WriteLine();
 
            Console.WriteLine("stu1 객체");
            Console.WriteLine($"Name = {stu.Name}, Age = {stu.Age}, Grade = {stu.Grade}");
        }
 
        /// <summary>
        /// 깊은 복사 메서드
        /// </summary>
        /// <typeparam name="Student"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static Student DeepClone<Student>(Student obj)
        {
            using (var ms = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(ms, obj);
                ms.Position = 0;
 
                return (Student)formatter.Deserialize(ms);
            }
        }
    }
 
    [Serializable]
    public class Student 
    {
        public string Name { get; set; }
        public string Age { get; set; }
        public string Grade { get; set; }
    }
}
 
cs

 

실행 결과

위와 같이 stu1 객체를 stu2 객체에 깊은 복사를 진행후, stu2Namestu1과 다르게 수정을 진행하였고 각각의 객체 정보를 출력 하니까 stu1Namestu2Name이 서로 다르게 출력된 것을 확인하실 수 있습니다.

 

만약 얕은 복사를 하였다면 stu1,stu2Name이 모두 범범조조2” 로 출력되었을 거에요~!

 

감사합니다.

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY