C# 中的 Array.AsReadOnly(T[]) 方法
csharpprogrammingserver side programming更新于 2025/9/20 8:46:00
C# 中的 Array.AsReadOnly(T[]) 方法返回指定数组的只读包装器,即只读的 ReadOnlyCollection<T>。
语法
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" };
// 只读 IList 包装器
IList<String> list = Array.AsReadOnly( arr );
// 显示只读 IList 的值。
Console.WriteLine( "Initial read-only IList..." );
display( list );
// 现在让我们更改只读包装器
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

