在C#中,要對ArrayList進行類型轉換,首先需要將ArrayList轉換為List
using System;
using System.Collections.ArrayList;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 創建一個包含不同類型對象的ArrayList
ArrayList arrayList = new ArrayList();
arrayList.Add("Hello");
arrayList.Add(42);
arrayList.Add(3.14);
// 將ArrayList轉換為List<object>
List<object> objectList = arrayList as List<object>;
// 遍歷List<object>并執行類型轉換
foreach (object item in objectList)
{
if (item is string str)
{
Console.WriteLine($"String: {str}");
}
else if (item is int num)
{
Console.WriteLine($"Int: {num}");
}
else if (item is double d)
{
Console.WriteLine($"Double: {d}");
}
}
}
}
在這個示例中,我們首先創建了一個包含不同類型對象的ArrayList。然后,我們使用as
關鍵字將其轉換為List