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

更新日期:2019-11-04

164 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始吧
廣告