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

C#에서 StringCollection이 읽기 전용인지 확인하는 방법

C#에서 StringCollection 컬렉션이 읽기 전용인지 확인하려면 IsReadOnly 속성을 사용하면 됩니다. 이 속성은 해당 컬렉션의 수정 가능 여부를 Boolean 값으로 반환합니다.

StringCollection.IsReadOnly 속성이란?

StringCollection 클래스의 IsReadOnly 속성은 현재 컬렉션이 읽기 전용인지 여부를 나타냅니다. 값이 True이면 컬렉션을 수정할 수 없고, False이면 요소를 추가하거나 제거할 수 있습니다.

예제 1: 숫자 배열로 확인하기

using System;
using System.Collections.Specialized;
public class Demo {
   public static void Main() {
      StringCollection stringCol = new StringCollection();
      String[] arr = new String[] { "100", "200", "300", "400", "500" };
      Console.WriteLine("배열 요소...");
      foreach (string res in arr) {
         Console.WriteLine(res);
      }
      stringCol.AddRange(arr);
      Console.WriteLine("StringCollection이 읽기 전용인가요? = " + stringCol.IsReadOnly);
      Console.WriteLine("지정한 문자열이 StringCollection에 있나요? = " + stringCol.Contains("800"));
   }
}

실행 결과

배열 요소...
100
200
300
400
500
StringCollection이 읽기 전용인가요? = False
지정한 문자열이 StringCollection에 있나요? = False

위 예제에서 IsReadOnly 속성은 False를 반환했습니다. 즉, 새로 생성한 StringCollection은 기본적으로 읽기 전용이 아니며 요소를 자유롭게 추가하거나 제거할 수 있습니다. 또한 Contains 메서드 결과에서 알 수 있듯이 컬렉션에 "800"이라는 문자열은 존재하지 않습니다.

예제 2: 문자열 배열로 확인하기

이번에는 이름으로 구성된 문자열 배열을 사용해 같은 방식을 다시 살펴보겠습니다.

using System;
using System.Collections.Specialized;
public class Demo {
   public static void Main() {
      StringCollection stringCol = new StringCollection();
      String[] arr = new String[] { "John", "Tim", "Kevin", "Bradman", "Katie", "Tom", "Nathan" };
      Console.WriteLine("문자열 배열 요소...");
      foreach (string res in arr) {
         Console.WriteLine(res);
      }
      stringCol.AddRange(arr);
      Console.WriteLine("StringCollection이 읽기 전용인가요? = " + stringCol.IsReadOnly);
      Console.WriteLine("지정한 문자열이 StringCollection에 있나요? = " + stringCol.Contains("Tim"));
   }
}

실행 결과

문자열 배열 요소...
John
Tim
Kevin
Bradman
Katie
Tom
Nathan
StringCollection이 읽기 전용인가요? = False
지정한 문자열이 StringCollection에 있나요? = True

두 번째 예제에서도 IsReadOnly 속성은 False를 반환했으며, AddRange 메서드로 추가된 "Tim"은 Contains 메서드로 조회 시 True가 나오는 것을 확인할 수 있습니다.

정리

일반적으로 new 키워드로 생성한 StringCollection 인스턴스는 읽기 전용이 아닙니다. IsReadOnly 속성은 주로 읽기 전용 래퍼(wrapper)로 감싸진 컬렉션을 다룰 때 유용하며, 코드에서 컬렉션을 수정하기 전에 미리 검사하여 런타임 오류(NotSupportedException)를 예방하는 데 활용할 수 있습니다.