C#의 Array.AsReadOnly(T[]) 메서드는 지정된 배열에 대한 읽기 전용 래퍼(읽기 전용 ReadOnlyCollection
구문
public static System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly<T> (T[] array);
여기서 T는 배열 요소의 유형이고 배열 T[]는 0부터 시작하는 1차원 배열입니다.
이제 Array.AsReadOnly(T[]) 메서드를 구현하는 예를 살펴보겠습니다. -
예시
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
String[] arr = { "John", "Tom", "Katie", "Brad" };
// read-only IList wrapper
IList<String> list = Array.AsReadOnly( arr );
// Display the values of the read-only IList.
Console.WriteLine( "Initial read-only IList..." );
display( list );
// Let us now change the read-only wrapper
try {
list[0] = "Kevin";
list[1] = "Bradley";
}
catch ( NotSupportedException e ) {
Console.WriteLine(e.GetType());
Console.WriteLine(e.Message );
Console.WriteLine();
}
Console.WriteLine( "After changing two elements, the IList remains the same since it is read-only..." );
display( list );
}
public static void display( IList<String> list ) {
for ( int i = 0; i < list.Count; i++ ) {
Console.WriteLine(list[i] );
}
Console.WriteLine();
}
} 출력
이것은 다음과 같은 출력을 생성합니다 -
Initial read-only IList... John Tom Katie Brad System.NotSupportedException Collection is read-only. After changing two elements, tthe IList remains the same since it is read-only... John Tom Katie Brad