Computer >> Máy Tính >  >> Lập trình >> C#

Phương thức Array.AsReadOnly (T []) trong C #

Phương thức Array.AsReadOnly (T []) trong C # trả về một trình bao bọc chỉ đọc cho mảng được chỉ định, đó là ReadOnlyCollection chỉ đọc .

Cú pháp

public static System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly<T> (T[] array);

Ở đây, T là kiểu của các phần tử của mảng, trong khi mảng T [] là mảng dựa trên 0 một chiều.

Bây giờ chúng ta hãy xem một ví dụ để triển khai phương thức Array.AsReadOnly (T []) -

Ví dụ

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();
   }
}

Đầu ra

Điều này sẽ tạo ra kết quả sau -

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