c#的List,

來源:互聯網
上載者:User

c#的List,
list

泛型集合,可以取代ArrayList

常用方法
List<int> list = new List<int>();
方法名 作用
Add() 添加元素
AddRange 添加一個集合
ToArray() 將集合轉數組

數組有個方法叫ToList(),可以將數組轉成集合;

為什麼用list 而不是ArrayList

裝箱與拆箱
把實值型別轉換為為參考型別叫裝箱,把參考型別轉換為實值型別稱為拆箱;
裝箱和拆箱會是運行時的操作,會使程式已耗用時間長,而使用泛型集合在編譯的時候產生的是指定的類型;
看兩種類型是否發生了裝箱或者拆箱,要看,這兩種類型是否存在繼承關係,有繼承關係才有可能發生裝箱操作;

類名 元素類型 是否發生拆裝箱 已耗用時間
list 確定且唯一 否 比較短
ArrayList 不確定,可有很多種 是 時間長
using System;using System.Collections;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Text;using System.Threading.Tasks;namespace List泛型集合{    class Program    {        static void Main(string[] args)        {            ArrayList list = new ArrayList();            //ArrayList 程式用時:00:00:00.1229805            //list      程式用時:00:00:00.0276141            //List<int> list = new List<int>();            list.Add(0);            list.Add(0);            Console.WriteLine(list.Count);            Stopwatch sw = new Stopwatch();            sw.Start();            for (int i = 0; i < 1000000; i++)            {                list.Add(i);            }            sw.Stop();            Console.WriteLine("程式用時:"+sw.Elapsed);            Console.ReadKey();        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.