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

C#에서 SortedList 개체의 크기가 고정되어 있는지 확인하는 방법

C#에서 SortedList 개체의 크기가 고정되어 있는지 확인하려면 IsFixedSize 속성을 사용하면 됩니다. 이 속성은 SortedList의 크기가 고정되어 있으면 True를 반환하고, 요소를 자유롭게 추가하거나 제거할 수 있다면 False를 반환합니다.

예제 1

다음은 SortedList 개체가 고정된 크기를 가지고 있는지 확인하는 코드입니다.

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      SortedList list = new SortedList();
      list.Add("1", "One");
      list.Add("2", "Two");
      list.Add("3", "Three");
      list.Add("4", "Four");
      list.Add("5", "Five");
      list.Add("6", "Six");
      list.Add("7", "Seven");
      list.Add("8", "Eight");
      Console.WriteLine("Key and Value of SortedList....");
      foreach(DictionaryEntry k in list )
      Console.WriteLine("Key: {0}, Value: {1}", k.Key , k.Value );
      Console.WriteLine("Is the SortedList having the value? "+list.ContainsValue("Three"));
      Console.WriteLine("The SortedList object has a fixed size? = "+list.IsFixedSize);
   }
}

출력 결과

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

Key and Value of SortedList....
Key: 1, Value: One
Key: 2, Value: Two
Key: 3, Value: Three
Key: 4, Value: Four
Key: 5, Value: Five
Key: 6, Value: Six
Key: 7, Value: Seven
Key: 8, Value: Eight
Is the SortedList having the value? True
The SortedList object has a fixed size? = False

출력 결과를 보면 ContainsValue() 메서드로 값 "Three"의 존재 여부를 확인한 결과 True가 반환되었으며, IsFixedSize 속성의 값은 False입니다. 즉, 이 SortedList는 크기가 고정되어 있지 않아 요소를 계속 추가할 수 있습니다.

예제 2

이번에는 다른 예제를 살펴보겠습니다.

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      SortedList list = new SortedList();
      list.Add("1", "John");
      list.Add("2", "Tim");
      list.Add("3", "Karl");
      list.Add("4", "Gary");
      list.Add("5", "Katie");
      Console.WriteLine("Key and Value of SortedList....");
      foreach(DictionaryEntry k in list )
      Console.WriteLine("Key: {0}, Value: {1}", k.Key , k.Value );
      Console.WriteLine("The SortedList object has a fixed size? = "+list.IsFixedSize);
   }
}

출력 결과

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

Key and Value of SortedList....
Key: 1, Value: John
Key: 2, Value: Tim
Key: 3, Value: Karl
Key: 4, Value: Gary
Key: 5, Value: Katie
The SortedList object has a fixed size? = False

정리

new 키워드로 생성한 일반적인 SortedList 개체는 기본적으로 크기가 고정되어 있지 않으므로 IsFixedSize 속성이 항상 False를 반환합니다. 반면, 고정된 크기를 가진 래퍼(wrapper)를 통해 생성된 SortedList는 True를 반환하게 됩니다. 컬렉션을 수정하기 전에 IsFixedSize 속성을 확인하면 런타임 오류인 NotSupportedException을 사전에 방지할 수 있습니다.