溫馨提示×

c# arraylist如何進行類型轉換

c#
小樊
147
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女