* Deep copy(깊은 복사)란?
Swallow copy(얕은 복사) 와 대비되는 개념으로 객체의 참조를 복사하는 것이 아니고 객체 자체를 복사한다!!
* 어떻게 하냐?
- List의 ConvertAll<T> 메서드를 활용
- String type 리스트(List<string>)의 경우 (string은 immutable 타입이기 때문에 아래와 같이 해도 된다!)
var deepList = list.ConvertAll(s => s);
- Custom object 리스트(List<TestObject>)의 경우
var deepList = list.ConvertAll(o => new TestObject(o.TestValue));
* 예제
class Program
{
private class TestObject
{
public TestObject(int value)
{
TestValue = value;
}
public int TestValue { get; set; }
}
static void Main(string[] args)
{
var obj1 = new TestObject(1);
var obj2 = new TestObject(2);
var list = new List<TestObject>();
list.Add(obj1);
list.Add(obj2);
// Swallow copy
TestObject[] swallowArray = new TestObject[2];
list.CopyTo(swallowArray);
// Deep copy
var deepList = list.ConvertAll(o => new TestObject(o.TestValue));
list[0].TestValue = 99999;
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine($"Original list [{i}] : TestValue {list[i].TestValue}");
}
for (int i = 0; i < swallowArray.Length; i++)
{
Console.WriteLine($"Swallow Copy [{i}] : TestValue {swallowArray[i].TestValue}");
}
for (int i = 0; i < deepList.Count; i++)
{
Console.WriteLine($"Deep Copy [{i}] : TestValue {deepList[i].TestValue}");
}
}
}
* 결과
![](https://t1.daumcdn.net/cfile/tistory/999F213A5C25AA3514)
* 다른 방법!
다음과 같이 Serialization(직렬화) 를 이용하여 깊은 복사를 수행하는 방법도 있다!! (이 방법이 더 유용할듯)
public static T DeepCopy<T>(T obj)
{
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, obj);
stream.Position = 0;
return (T)formatter.Deserialize(stream);
}
}