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

C#에서 SortedList가 읽기 전용인지 확인하는 방법

C#에서 SortedList 컬렉션이 읽기 전용(read-only) 상태인지 확인하려면 IsReadOnly 속성을 사용하면 됩니다. 이 속성은 컬렉션에 대한 수정이 허용되지 않으면 true를, 요소의 추가·수정·삭제가 가능하면 false를 반환합니다.

아래 예제를 통해 실제 동작 과정을 살펴보겠습니다.

예제 1

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("\n값 목록 출력...");
      IList col = list.GetValueList();
      foreach(string res in col) {
         Console.WriteLine(res);
      }

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

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

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

값 목록 출력...
Sales
Purchase
IT
Finance
Marketing
Operations

SortedList는 읽기 전용인가? = False

실행 결과 IsReadOnly 속성이 False를 반환했습니다. 즉, 이 SortedList에는 새로운 요소를 추가하거나 기존 요소를 수정·삭제하는 것이 자유롭다는 의미입니다. 또한 GetValueList() 메서드를 사용하면 키 순서대로 정렬된 값들의 목록을 손쉽게 가져올 수 있습니다.

예제 2

이번에는 특정 키의 인덱스 조회와 키 컬렉션 출력을 함께 살펴보면서 읽기 전용 여부를 확인해 보겠습니다.

using System;
using System.Collections;

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

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

      Console.WriteLine("\n'One' 키의 인덱스 = " + list.IndexOfKey("One"));

      ICollection col = list.Keys;
      Console.WriteLine("\n키 컬렉션...");
      foreach(string res in col)
         Console.WriteLine(res);

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

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

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

'One' 키의 인덱스 = 2

키 컬렉션...
Five
Four
One
Six
Three
Two

SortedList는 읽기 전용인가? = False

IndexOfKey() 메서드는 지정한 키가 저장된 인덱스 위치를 반환하며, 키가 존재하지 않으면 -1을 반환합니다. 위 예제에서는 'One' 키가 인덱스 2번째 위치에 있음을 확인할 수 있습니다.

정리

IsReadOnly 속성은 IList 인터페이스에서 제공되며, SortedList가 읽기 전용이면 true를 반환합니다. 참고로 new 키워드로 직접 생성한 SortedList는 항상 쓰기 가능(writable)하므로 이 속성은 일반적으로 false를 반환합니다. true가 반환되는 경우는 컬렉션이 읽기 전용 래퍼(wrapper)로 감싸져 있어 요소 수정이 차단된 경우입니다. 따라서 컬렉션을 변경하기 전에 이 속성을 검사하면 불필요한 예외 발생을 예방할 수 있습니다.