C# 中 Array.AsReadOnly(T[]) 方法
C# 中的 Array.AsReadOnly(T[]) 方法为指定数组返回一个只读包装器,即只读的 ReadOnlyCollection<T>。
语法
public static System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly<T> (T[] array);
此处,T 是数组元素的类型,而 array 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP