Phương thức Array.AsReadOnly<T>() trong C# trả về một wrapper chỉ đọc (ReadOnlyCollection<T>) cho mảng được chỉ định.
Cú pháp
public static System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly<T>(T[] array);
Trong đó:
T: Kiểu dữ liệu của các phần tử mảngarray: Mảng một chiều, zero-based cần tạo wrapper chỉ đọc
Ví dụ
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
String[] arr = { "John", "Tom", "Katie", "Brad" };
// Tạo wrapper IList chỉ đọc
IList list = Array.AsReadOnly(arr);
// Hiển thị giá trị ban đầu
Console.WriteLine("Danh sách chỉ đọc ban đầu...");
Display(list);
// Thử thay đổi wrapper chỉ đọc
try
{
list[0] = "Kevin";
list[1] = "Bradley";
}
catch (NotSupportedException e)
{
Console.WriteLine(e.GetType());
Console.WriteLine(e.Message);
Console.WriteLine();
}
Console.WriteLine("Sau khi thử thay đổi, danh sách vẫn không đổi vì là chỉ đọc...");
Display(list);
}
public static void Display(IList list)
{
for (int i = 0; i < list.Count; i++)
Console.WriteLine(list[i]);
Console.WriteLine();
}
}
Kết quả
Danh sách chỉ đọc ban đầu... John Tom Katie Brad System.NotSupportedException Collection is read-only. Sau khi thử thay đổi, danh sách vẫn không đổi vì là chỉ đọc... John Tom Katie Brad
Lưu ý quan trọng: Wrapper chỉ đọc ngăn chặn việc sửa đổi thông qua wrapper, nhưng mảng gốc vẫn có thể bị thay đổi trực tiếp. Để bảo vệ hoàn toàn, hãy không công khai mảng gốc.