เมธอด Array.AsReadOnly(T[]) ใน C# ส่งคืน wrapper แบบอ่านอย่างเดียวสำหรับอาร์เรย์ที่ระบุ ซึ่งเป็น ReadOnlyCollection
ไวยากรณ์
public static System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly<T> (T[] array);
โดยที่ T คือประเภทขององค์ประกอบของอาร์เรย์ ในขณะที่อาร์เรย์ T[] คืออาร์เรย์แบบอิงศูนย์แบบหนึ่งมิติ
ให้เรามาดูตัวอย่างการใช้เมธอด 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