C#中数组Array,ArrayList,泛型List详细对比_C#教程

在C#中数组Array,ArrayList,泛型List都能够存储一组对象,但是在开发中根本不知道用哪个性能最高,下面我们慢慢分析分析。

一、数组Array

数组是一个存储相同类型元素的固定大小的顺序集合。数组是用来存储数据的集合,通常认为数组是一个同一类型变量的集合。

Array 类是 C# 中所有数组的基类,它是在 System 命名空间中定义。

数组在内存中是连续存储的,所以它的索引速度非常快,而且赋值与修改元素也非常简单。

Array数组具体用法:

using System;

namespace WebApp
{
  class Program
  {
    static void Main(string[] args)
    {
      //System.Array
      //1、数组[] 特定类型、固定长度
      string[] str1 = new string[3];
      str1[0] = "a";
      str1[1] = "b";
      str1[2] = "c";
      Console.WriteLine(str1[2]);

      string[] str2 = new string[] { "a", "b", "c" };
      Console.WriteLine(str2[0]);

      string[] str3 = { "a", "b", "c" };
      Console.WriteLine(str3[0]);
      //2、二维数组
      //int[,] intArray=new int[2,3]{{1,11,111},{2,22,222}};
      int[,] intArray = new int[2, 3];
      intArray[0, 0] = 1;
      intArray[0, 1] = 11;
      intArray[0, 2] = 111;

      intArray[1, 0] = 2;
      intArray[1, 1] = 22;
      intArray[1, 2] = 222;
      Console.WriteLine("{0},{1},{2}", intArray[0, 0], intArray[0, 1], intArray[0, 2]);
      Console.WriteLine("{0},{1},{2}", intArray[1, 0], intArray[1, 1], intArray[1, 2]);

      //3、多维数组
      int[, ,] intArray1 = new int[,,]
      {
        {{1, 1}, {11, 11}, {111, 111}},
        {{2, 2}, {22, 22}, {222, 222}},
        {{3, 3}, {33, 33}, {333, 333}}
      };
      Console.WriteLine("{0},{1},{2},{3},{4},{5}", intArray1[0, 0, 0], intArray1[0, 0, 1], intArray1[0, 1, 0], intArray1[0, 1, 1],
        intArray1[0, 2, 0], intArray1[0, 2, 1]);
      Console.WriteLine("{0},{1},{2},{3},{4},{5}", intArray1[1, 0, 0], intArray1[1, 0, 1], intArray1[1, 1, 0], intArray1[1, 1, 1],
        intArray1[1, 2, 0], intArray1[1, 2, 1]);
      Console.WriteLine("{0},{1},{2},{3},{4},{5}", intArray1[2, 0, 0], intArray1[2, 0, 1], intArray1[2, 1, 0], intArray1[2, 1, 1],
        intArray1[2, 2, 0], intArray1[2, 2, 1]);

      //4、交错数组即数组的数组
      int[][] intArray2 = new int[4][];
      intArray2[0] = new int[] { 1 };
      intArray2[1] = new int[] { 2, 22 };
      intArray2[2] = new int[] { 3, 33, 333 };
      intArray2[3] = new int[] { 4, 44, 444,4444 };
      for (int i = 0; i < intArray2.Length; i++)
      {
        for (int j = 0; j < intArray2[i].Length; j++)
        {
          Console.WriteLine("{0}", intArray2[i][j]);
        }
      }

      Console.ReadKey();
    }
  }
}

数组虽然存储检索数据很快,但是也有一些缺点:

1、在声明数组的时候必须指定数组的长度,如果不清楚数组的长度,就会变得很麻烦。

2、数组的长度太长,会造成内存浪费;太短会造成数据溢出的错误。

3、在数组的两个数据间插入数据是很麻烦的

更多参考微软官方文档:Array 类 (System)

二、ArrayList

既然数组有很多缺点,C#就提供了ArrayList对象来克服这些缺点。

ArrayList是在命名空间System.Collections下,在使用该类时必须进行引用,同时继承了IList接口,提供了数据存储和检索。

ArrayList对象的大小是按照其中存储的数据来动态扩充与收缩的。因此在声明ArrayList对象时并不需要指定它的长度。

ArrayList 的默认初始容量为 0。随着元素添加到 ArrayList 中,容量会根据需要通过重新分配自动增加。可通过调用 TrimToSize 或通过显式设置 Capacity 属性减少容量。

using System;
using System.Collections;
public class SamplesArrayList {

  public static void Main() {

   ArrayList myAL = new ArrayList();
   myAL.Add("Hello");
   myAL.Add("World");
   myAL.Add("!");

   Console.WriteLine( "myAL" );
   Console.WriteLine( "  Count:  {0}", myAL.Count );
   Console.WriteLine( "  Capacity: {0}", myAL.Capacity );
   Console.Write( "  Values:" );
   PrintValues( myAL );
  }

  public static void PrintValues( IEnumerable myList ) {
   foreach ( Object obj in myList )
     Console.Write( "  {0}", obj );
   Console.WriteLine();
   Console.ReadKey();
  }

}

运行结果:

ArrayList解决了数组中所有的缺点,但是在存储或检索值类型时通常发生装箱和取消装箱操作,带来很大的性能耗损。尤其是装箱操作,例如:

      ArrayList list = new ArrayList();

      //add
      list.Add("joye.net");
      list.Add(27);

      //update
      list[2] = 28;

      //delete
      list.RemoveAt(0);

      //Insert
      list.Insert(0, "joye.net1"); 

在List中,先插入了字符串joye.net,而且插入了int类型27。这样在ArrayList中插入不同类型的数据是允许的。因为ArrayList会把所有插入其中的数据当作为object类型来处理,在使用ArrayList处理数据时,很可能会报类型不匹配的错误,也就是ArrayList不是类型安全的。

更多参考微软官方ArrayList文档:ArrayList 类 (System.Collections)

三、泛型List<T>

由于ArrayList存在不安全类型与装箱拆箱的缺点,所以出现了泛型的概念。

List 类是 ArrayList 类的泛型等效类。该类使用大小可按需动态增加的数组实现 IList 泛型接口,大部分用法都与ArrayList相似。

List<T> 是类型安全的,在声明List集合时,必须为其声明List集合内数据的对象类型。

using System;
using System.Collections.Generic;

public class Example
{
  public static void Main()
  {
    List<string> dinosaurs = new List<string>();

    Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);

    dinosaurs.Add("Tyrannosaurus");
    dinosaurs.Add("Amargasaurus");
    dinosaurs.Add("Mamenchisaurus");
    dinosaurs.Add("Deinonychus");
    dinosaurs.Add("Compsognathus");

    Console.WriteLine();
    foreach(string dinosaur in dinosaurs)
    {
      Console.WriteLine(dinosaur);
    }

    Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);
    Console.WriteLine("Count: {0}", dinosaurs.Count);

    Console.WriteLine("\nContains(\"Deinonychus\"): {0}",
      dinosaurs.Contains("Deinonychus"));

    Console.WriteLine("\nInsert(2, \"Compsognathus\")");
    dinosaurs.Insert(2, "Compsognathus");

    Console.WriteLine();
    foreach(string dinosaur in dinosaurs)
    {
      Console.WriteLine(dinosaur);
    }

    Console.WriteLine("\ndinosaurs[3]: {0}", dinosaurs[3]);

    Console.WriteLine("\nRemove(\"Compsognathus\")");
    dinosaurs.Remove("Compsognathus");

    Console.WriteLine();
    foreach(string dinosaur in dinosaurs)
    {
      Console.WriteLine(dinosaur);
    }

    dinosaurs.TrimExcess();
    Console.WriteLine("\nTrimExcess()");
    Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
    Console.WriteLine("Count: {0}", dinosaurs.Count);

    dinosaurs.Clear();
    Console.WriteLine("\nClear()");
    Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
    Console.WriteLine("Count: {0}", dinosaurs.Count);
  }
}

如果声明List集合内数据的对象类型是string,然后往List集合中插入int类型的111,IDE就会报错,且不能通过编译。显然这样List<T>是类型安全的。

对返回结果集再封装:

  public class ResultDTO<T>
  {
    public T Data { get; set; }
    public string Code { get; set; }
    public string Message { get; set; }
  }

      var data = new CityEntity();
      return new ResultDTO<CityEntity> { Data = data, Code = "1", Message = "sucess"};

      var data2 = new List<CityEntity>();
      return new ResultDTO<List<CityEntity>> { Data = data2, Code = "1", Message = "sucess" };

      var data1 = 1;
      return new ResultDTO<int> { Data = data1, Code = "1", Message = "sucess" };

更多参考微软官方文档:List泛型类

四、总结

1、数组的容量固定,而ArrayList或List<T>的容量可根据需要自动扩充。

2、数组可有多个维度,而 ArrayList或 List< T> 始终只有一个维度。(可以创建数组列表或列表的列表)

3、特定类型的数组性能优于 ArrayList的性能(不包括Object,因为 ArrayList的元素是 Object ,在存储或检索值类型时通常发生装箱和取消装箱操作)。

4、 ArrayList 和 List<T>基本等效,如果List< T> 类的类型T是引用类型,则两个类的行为是完全相同的。如果T是值类型,需要考虑装箱和拆箱造成的性能损耗。List<T> 是类型安全。

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索java
, arraylist
, list
, 泛型
, array
arraylist泛型
c站、c语言、cf、ch、c罗,以便于您获取更多的相关知识。

时间: 2024-08-03 10:33:53

C#中数组Array,ArrayList,泛型List详细对比_C#教程的相关文章

asp.net c#中[],List,Array,ArrayList的区别

asp教程.net c#中[],List,Array,ArrayList的区别 [] 是针对特定类型.固定长度的. List 是针对特定类型.任意长度的. List 类是 ArrayList 类的泛型等效类,某些情况下,用它比用数组和 ArrayList 都方便. 我们假设有一组数据,其中每一项数据都是一个结构. public struct Item {     public int Id;     public string DisplayText; } 注意结构是不能给实例字段赋值的,即 p

JS中数组Array的用法示例介绍

 这篇文章主要介绍了JS中数组Array的用法,需要的朋友可以参考下 new Array()  new Array(len)  new Array([item0,[item1,[item2,...]]]  使用数组对象的方法:  var objArray=new Array();  objArray.concact([item1[,item2[,....]]]-------------------将参数列表连接到objArray的后面形成一个新的数组并返回,原有数组不受影响.如:var arr=

C#中数组、ArrayList和List三者的区别详解及实例_C#教程

在C#中数组,ArrayList,List都能够存储一组对象,那么这三者到底有什么样的区别呢. 数组 数组在C#中最早出现的.在内存中是连续存储的,所以它的索引速度非常快,而且赋值与修改元素也很简单. //数组 string[] s=new string[2]; //赋值 s[0]="a"; s[1]="b"; //修改 s[1]="a1"; 但是数组存在一些不足的地方.在数组的两个数据间插入数据是很麻烦的,而且在声明数组的时候必须指定数组的长度

C#中数组、ArrayList和List三者的区别详解_C#教程

在C#中数组,ArrayList,List都能够存储一组对象,那么这三者到底有什么样的区别呢. 数组 数组在C#中最早出现的.在内存中是连续存储的,所以它的索引速度非常快,而且赋值与修改元素也很简单. //数组 string[] s=new string[2]; //赋值 s[0]="a"; s[1]="b"; //修改 s[1]="a1";  但是数组存在一些不足的地方.在数组的两个数据间插入数据是很麻烦的,而且在声明数组的时候必须指定数组的长

js中数组(Array)的排序(sort)注意事项说明

 本篇文章主要是对js中数组(Array)的排序(sort)注意事项进行了说明介绍,需要的朋友可以过来参考下,希望对大家有所帮助 直接看代码吧,测试结果也贴在里面了    代码如下: var arrDemo = new Array();    arrDemo[0] = 10;  arrDemo[1] = 50;  arrDemo[2] = 51;  arrDemo[3] = 100;    arrDemo.sort(); //调用sort方法后,数组本身会被改变,即影响原数组    alert(

C#中数组、ArrayList与List对象的区别

在C#中,当我们想要存储一组对象的时候,就会想到用数组,ArrayList,List这三个对象了.那么这三者到底有什么样的区别呢? 我们先来了解一下数组,因为数组在C#中是最早出现的. 数组 数组有很多的优点,比如说数组在内存中是连续存储的,所以它的索引速度是非常的快,而且赋值与修改元素也很简单,比如: string[] s=new string[3]; //赋值 s[0]="a"; s[1]="b"; s[2]="c"; //修改 s[1]=&

将json字符串中数组节点转换为泛型list集合(gson)

开发中需要将json中节点单独取出某个节点,解析获取数据,此处对json字符串节点中数组节点,转换为泛型list集合,使用gson. google的gson的pom文件和jar:gson 代码如下: package my.demo.java.z.generic; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import com.google.gson

C# 泛型深入理解介绍_C#教程

引言: 在上一个专题中介绍了C#2.0 中引入泛型的原因以及有了泛型后所带来的好处,然而上一专题相当于是介绍了泛型的一些基本知识的,对于泛型的性能为什么会比非泛型的性能高却没有给出理由,所以在这个专题就中将会介绍原因和一些关于泛型的其他知识. 一.泛型类型和类型参数 泛型类型和其他int,string一样都是一种类型,泛型类型有两种表现形式的:泛型类型(包括类.接口.委托和结构,但是没有泛型枚举的)和泛型方法.那什么样的类.接口.委托和方法才称作泛型类型的呢 ?我的理解是类.接口.委托.结构或方

详解C#中委托,事件与回调函数讲解_C#教程

.Net编程中最经常用的元素,事件必然是其中之一.无论在ASP.NET还是WINFrom开发中,窗体加载(Load),绘制(Paint),初始化(Init)等等. "protected void Page_Load(object sender, EventArgs e)"这段代码相信没有人不熟悉的.细心一点一定会发现,非常多的事件方法都是带了"object sender, EventArgs e"这两个参数.这是不是和委托非常相似呢? 一.委托(有些书中也称为委派)