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

C#에서 OrderedDictionary 컬렉션이 읽기 전용인지 확인하는 방법

C#에서 OrderedDictionary 컬렉션이 읽기 전용(Read-Only)인지 확인하려면 IsReadOnly 속성을 사용합니다. 이 속성은 해당 컬렉션에 요소를 추가, 수정, 삭제할 수 있는지 여부를 불리언(Boolean) 값으로 반환합니다.

IsReadOnly 속성이란?

IsReadOnly는 IDictionary 인터페이스에서 제공하는 속성으로, 반환값은 다음과 같습니다.

  • true : 컬렉션이 읽기 전용이어서 요소를 변경할 수 없습니다.
  • false : 컬렉션을 자유롭게 수정할 수 있습니다.

new 키워드로 직접 생성한 OrderedDictionary는 기본적으로 읽기 전용이 아니기 때문에 대부분 false가 반환됩니다.

예제 1

다음 예제에서는 OrderedDictionary에 여러 개의 키와 값을 추가한 뒤, 저장된 값을 출력하고 IsReadOnly 속성과 Contains 메서드의 결과를 함께 확인합니다.

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add("1", "One");
      dict.Add("2", "Two");
      dict.Add("3", "Three");
      dict.Add("4", "Four");
      dict.Add("5", "Five");
      dict.Add("6", "Six");
      dict.Add("7", "Seven");
      dict.Add("8", "Eight");
      ICollection col = dict.Values;
      String[] strVal = new String[dict.Count];
      col.CopyTo(strVal, 0);
      Console.WriteLine("Displaying the values...");
      for (int i = 0; i < dict.Count; i++) {
         Console.WriteLine(strVal[i]);
      }
      Console.WriteLine("If OrderedDictionary read-only? = " + dict.IsReadOnly);
      Console.WriteLine("The OrderedDictionary has the key 15? = " + dict.Contains("15"));
      Console.WriteLine("The OrderedDictionary has the key 5? = " + dict.Contains("5"));
   }
}

실행 결과

Displaying the values...
One
Two
Three
Four
Five
Six
Seven
Eight
If OrderedDictionary read-only? = False
The OrderedDictionary has the key 15? = False
The OrderedDictionary has the key 5? = True

코드 설명

  • dict.Values : OrderedDictionary에 저장된 모든 값을 ICollection 형태로 가져옵니다.
  • CopyTo(strVal, 0) : 가져온 값들을 문자열 배열 strVal의 0번 인덱스부터 복사합니다.
  • dict.IsReadOnly : 컬렉션이 읽기 전용인지 확인합니다. 일반적인 인스턴스이므로 False가 출력됩니다.
  • dict.Contains("15") : 키 "15"가 존재하지 않으므로 False를 반환합니다.
  • dict.Contains("5") : 키 "5"가 존재하므로 True를 반환합니다.

예제 2

이번에는 문자열 키를 사용하는 또 다른 예제입니다. 열 가지 항목을 추가한 뒤 동일한 방식으로 읽기 전용 여부와 특정 키의 존재 여부를 확인해 보겠습니다.

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add("A", "Pen");
      dict.Add("B", "Pencil");
      dict.Add("C", "Notebook");
      dict.Add("D", "Table");
      dict.Add("E", "Chair");
      dict.Add("F", "Coworking");
      dict.Add("G", "Cubicle");
      dict.Add("H", "Sticky Notes");
      dict.Add("I", "WhiteBoard");
      dict.Add("J", "Marker");
      ICollection col = dict.Values;
      String[] strVal = new String[dict.Count];
      col.CopyTo(strVal, 0);
      Console.WriteLine("Displaying the values...");
      for (int i = 0; i < dict.Count; i++) {
         Console.WriteLine(strVal[i]);
      }
      Console.WriteLine("If OrderedDictionary read-only? = " + dict.IsReadOnly);
      Console.WriteLine("The OrderedDictionary has the key B? = " + dict.Contains("B"));
   }
}

실행 결과

Displaying the values...
Pen
Pencil
Notebook
Table
Chair
Coworking
Cubicle
Sticky Notes
WhiteBoard
Marker
If OrderedDictionary read-only? = False
The OrderedDictionary has the key B? = True

정리

OrderedDictionary의 IsReadOnly 속성은 컬렉션을 수정하기 전에 상태를 안전하게 검사할 수 있게 해주는 간단하면서도 유용한 도구입니다. 특히 외부에서 전달받은 컬렉션을 다룰 때 읽기 전용 여부를 미리 확인하면 런타임 예외(NotSupportedException)를 예방할 수 있습니다. 아울러 Contains 메서드를 함께 활용하면 특정 키의 존재 여부도 손쉽게 검증할 수 있습니다.