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