c# - 泛型集合

创建泛型集合对象:

泛型集合类型一旦确定,那么里边的元素类型也随之确定(它与数组类似)

static void Main(string[] args)
{
    // 创建一个整数泛型集合
    List<int> num = new List<int>();
}

向泛型集合添加元素:

static void Main(string[] args)
{
    // 创建一个整数泛型集合
    List<int> num = new List<int>();
    num.Add(1);
    num.AddRange(new int[]{ 1, 2, 3, 4 });
    for (int i = 0; i < num.Count; i ++)
    {
        Console.WriteLine(num[i]); // 1 1 2 3 4
    }
    Console.ReadLine();
}

泛型集合的方法与ArrayList一样,请参考之前ArrayList文章。

泛型集合转数组:

ToArray( ) 方法可以使泛型集合转数组

注意: 最后转成的数组类型取决于 泛型集合的类型。

static void Main(string[] args)
{
    // 创建一个整数泛型集合
    List<int> num = new List<int>();
    num.AddRange(new int[]{ 1, 2, 3, 4 });
    int[] res = num.ToArray();
}

数组转泛型集合:

ToList( ) 方法可以使数组转泛型集合

static void Main(string[] args)
{
    string[] str = new string[]{"1", "2", "3"};
    List<string> res =str.ToList();
    Console.WriteLine(res.GetType()); // System.Collections.Generic.List`1[System.String]
    Console.ReadLine();
}

猜你喜欢

转载自blog.csdn.net/qq_42778001/article/details/109105367
今日推荐