在 C# 中將 ArrayList 轉換成陣列


要在 C# 中將 ArrayList 轉換成陣列,請使用 ToArray() 方法。

首先,建立一個 ArrayList −

ArrayList arrList = new ArrayList();
arrList.Add("one");
arrList.Add("two");
arrList.Add("three");

轉換時,請使用 ToArray() 方法 −

arrList.ToArray(typeof(string)) as string[];

我們來看看完整的程式碼 −

示例

 即時演練

using System;
using System.Collections;

public class Program {
   public static void Main() {
      ArrayList arrList = new ArrayList();
      arrList.Add("one");
      arrList.Add("two");
      arrList.Add("three");

      string[] arr = arrList.ToArray(typeof(string)) as string[];

      foreach (string res in arr) {
         Console.WriteLine(res);
      }
   }
}

輸出

one
two
three

更新於:2020-06-22

1000+ 瀏覽

開啟你的職業生涯

完成課程,獲得資格認證

開始學習
廣告
© . All rights reserved.