温馨提示×

c# arraylist如何进行类型转换

c#
小樊
150
2024-11-15 23:51:15
栏目: 编程语言

在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。接下来,我们遍历List并执行类型转换,以获取每个对象的实际类型。

0