C#中的Array.AsReadOnly(T [])方法
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
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语