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 迎新祝福语简短20字
13 女侠老师祝福语简短
14 好姐妹生日祝福语 简短
15 新婚祝福语简短十六字
16 生日祝福语简短激励女生
17 写生日祝福语简短唯美
18 老婆生日祝福语短句简短