Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C#에서 SortedList 객체의 얕은 복사본 만드는 방법 (Clone() 메서드 활용)

C#에서 SortedList 객체의 얕은 복사본(shallow copy)을 생성하려면 Clone() 메서드를 사용하면 됩니다. 이 메서드는 컬렉션의 구조와 키 정렬 정보만 새 인스턴스로 복제하며, 내부에 저장된 개별 요소(참조 형식 객체)까지 깊게 복사하지 않는다는 점이 특징입니다.

예제 1: Clone()으로 SortedList 복제하기

using System;
using System.Collections;

public class Demo {
   public static void Main(String[] args){
      SortedList list = new SortedList();
      list.Add("A", "Jacob");
      list.Add("B", "Sam");
      list.Add("C", "Tom");
      list.Add("D", "John");
      list.Add("E", "Tim");
      list.Add("F", "Mark");
      list.Add("G", "Gary");
      list.Add("H", "Nathan");
      list.Add("I", "Shaun");
      list.Add("J", "David");

      Console.WriteLine("SortedList 요소...");
      foreach(DictionaryEntry d in list){
         Console.WriteLine(d.Key + " " + d.Value);
      }

      ICollection col1 = list.Values;
      Console.WriteLine("\n값 목록...");
      foreach(string s in col1)
         Console.WriteLine(s);

      ICollection col2 = list.Keys;
      Console.WriteLine("\n키 목록...");
      foreach(string s in col2)
         Console.WriteLine(s);

      SortedList list2 = (SortedList)list.Clone();
      Console.WriteLine("\n복제된 SortedList 결과...");
      foreach(DictionaryEntry d in list){
         Console.WriteLine(d.Key + " " + d.Value);
      }
   }
}

실행 결과

SortedList 요소...
A Jacob
B Sam
C Tom
D John
E Tim
F Mark
G Gary
H Nathan
I Shaun
J David

값 목록...
Jacob
Sam
Tom
John
Tim
Mark
Gary
Nathan
Shaun
David

키 목록...
A
B
C
D
E
F
G
H
I
J

복제된 SortedList 결과...
A Jacob
B Sam
C Tom
D John
E Tim
F Mark
G Gary
H Nathan
I Shaun
J David

코드 설명

Clone() 메서드의 반환 타입은 object이므로, 반드시 (SortedList)로 명시적 캐스팅을 해야 합니다. 위 실행 결과에서 볼 수 있듯이, 복제된 리스트는 원본과 동일한 키-값 쌍을 키 기준으로 정렬된 상태 그대로 유지합니다.

예제 2: GetValueList()와 IsReadOnly 함께 확인하기

이번에는 GetValueList()로 값 목록을 가져오고, IsReadOnly 속성으로 읽기 전용 여부를 확인한 뒤 복제하는 예제입니다.

using System;
using System.Collections;

public class Demo {
   public static void Main(String[] args){
      SortedList list = new SortedList();
      list.Add("One", "IT");
      list.Add("Two ", "Operations");
      list.Add("Three", "Marketing");
      list.Add("Four", "Purchase");
      list.Add("Five", "Sales");
      list.Add("Six", "Finance");

      Console.WriteLine("SortedList 요소...");
      foreach(DictionaryEntry d in list){
         Console.WriteLine(d.Key + " " + d.Value);
      }

      Console.WriteLine("\nSortedList 값 목록...");
      IList col = list.GetValueList();
      foreach(string res in col) {
         Console.WriteLine(res);
      }

      Console.WriteLine("\nSortedList가 읽기 전용인가요? = " + list.IsReadOnly);

      SortedList list2 = (SortedList)list.Clone();
      Console.WriteLine("\n복제된 SortedList 결과...");
      foreach(DictionaryEntry d in list){
         Console.WriteLine(d.Key + " " + d.Value);
      }
   }
}

실행 결과

SortedList 요소...
Five Sales
Four Purchase
One IT
Six Finance
Three Marketing
Two Operations

SortedList 값 목록...
Sales
Purchase
IT
Finance
Marketing
Operations

SortedList가 읽기 전용인가요? = False

복제된 SortedList 결과...
Five Sales
Four Purchase
One IT
Six Finance
Three Marketing
Two Operations

정리 및 주의 사항

  • 얕은 복사(Shallow Copy): Clone()은 SortedList의 구조(키 정렬 정보 포함)만 새 인스턴스로 복사하며, 값으로 저장된 참조 객체들은 원본과 계속 공유됩니다.
  • 깊은 복사(Deep Copy): 저장된 객체 자체까지 완전히 독립적인 복사본이 필요하다면 직렬화(Serialization)를 이용하거나, 컬렉션을 직접 순회하며 새 객체를 생성하는 방식을 사용해야 합니다.
  • Clone()의 반환 타입은 object이므로 사용 전 반드시 SortedList로 캐스팅해야 합니다.
  • 복제본에 요소를 추가하거나 삭제해도 원본 SortedList에는 영향을 주지 않습니다.