C# arrayList陣列轉成list陣列
阿新 • • 發佈:2019-01-04
attachment是一個動態陣列(ArrayList)
ArrayList可以儲存任何型別的物件。attachments.Add(Object value)
List<string> files = new List<string>((string[])attachments.ToArray(typeof(string)));
ArrayList不能通過。toList()等簡單方式轉換。上網查了好久都沒有例項所以在這寫一下。
List是一個介面,例項化時要說明型別
List<string> list1=new list<string>(字串陣列);。。
所以動態陣列只能先轉換為字串陣列才能構造List物件
(string[])attachments.ToArray(typeof(string))
using System; using System.Collections; using System.Collections.Generic; namespace test { class Program { static void Main(string[] args) { ArrayList attachments = new ArrayList(); attachments.Add("字串1"); attachments.Add("字串2"); attachments.Add("字串3"); List<string> files = new List<string>((string[])attachments.ToArray(typeof(string))); foreach (string file in files) Console.WriteLine(file.ToString()); Console.ReadLine();//等待輸入,防止除錯視窗關閉 } } }