用 C# 為 ArrayList 建立一個只讀包裝


為了為 ArrayList 建立只讀包裝,程式碼如下所示 −

示例

 動態演示

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      ArrayList list = new ArrayList();
      list.Add("One");
      list.Add("Two");
      list.Add("Three");
      list.Add("Four");
      list.Add("Five");
      list.Add("Six");
      list.Add("Seven");
      list.Add("Eight");
      Console.WriteLine("ArrayList elements...");
      foreach(string str in list){
         Console.WriteLine(str);
      }
      Console.WriteLine("ArrayList is read-only? = "+list.IsReadOnly);
   }
}

輸出

這將生成以下輸出 −

ArrayList elements...
One
Two
Three
Four
Five
Six
Seven
Eight
ArrayList is read-only? = False

示例

現在我們再看另一個示例 −

 動態演示

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      ArrayList list = new ArrayList();
      list.Add("One");
      list.Add("Two");
      list.Add("Three");
      list.Add("Four");
      list.Add("Five");
      list.Add("Six");
      list.Add("Seven");
      list.Add("Eight");
      Console.WriteLine("ArrayList elements...");
      foreach(string str in list){
         Console.WriteLine(str);
      }
      Console.WriteLine("ArrayList is read-only? = "+list.IsReadOnly);
      ArrayList list2 = ArrayList.ReadOnly(list);
      Console.WriteLine("ArrayList is read-only now? = "+list2.IsReadOnly);
   }
}

輸出

這將生成以下輸出 −

ArrayList elements...
One
Two
Three
Four
Five
Six
Seven
Eight
ArrayList is read-only? = False ArrayList is read-only now? = True

更新於: 05-Dec-2019

138 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

立即開始
廣告