最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
asp.net c#中[],List,Array,ArrayList的区别
时间:2022-06-25 08:28:08 编辑:袖梨 来源:一聚教程网
asp教程.net c#中[],List,Array,ArrayList的区别
[] 是针对特定类型、固定长度的。
List 是针对特定类型、任意长度的。
List 类是 ArrayList 类的泛型等效类,某些情况下,用它比用数组和 ArrayList 都方便。
我们假设有一组数据,其中每一项数据都是一个结构。
public struct Item
{
public int Id;
public string DisplayText;
}
注意结构是不能给实例字段赋值的,即 public int Id = 1 是错误的。using System.Collections.Generic;
List
- items = new List
- ();
//添加
Item item1 = new Item();
item1.Id = 0;
item1.DisplayText = "水星";
items.Add(item1);//添加
Item item2 = new Item();
item2.Id = 1;
item2.DisplayText = "地球";
items.Add(item2);
//修改
//这里使用的是结构,故不能直接用 items[1].DisplayText = "金星";,如果 Item 是类,则可以直接用。为什么呢?因为结构是按值传递的。
Item item = items[1];
item.DisplayText = "金星";
items[1] = item;
Array 是针对任意类型、固定长度的。
private void Change(Array array)
{
for (int i = 0; i < array.Length; i++) // 使用 Length
{
array.SetValue((int)array.GetValue(i) * 2, i); // 需要类型转换
}
}
ArrayList 是针对任意类型、任意长度的。
和数组不同,ArrayList 的各个元素的类型可以不同。
声明对象
//声明 ArrayList 有三种重载方法,较常用的有两种
ArrayList al = new ArrayList();
ArrayList al = new ArrayList(3);
上例中,参数值 3 表示容量,即可以容纳多少个元素
Array 和 ArrayList 是通过存储 object 实现任意类型的,所以使用时要转换。
相关文章
- 荧光深渊好玩吗 荧光深渊手游深度体验与玩法解析 03-30
- 彩虹之光开荒玩法全解析 彩虹之光新手开荒攻略与资源规划指南 03-30
- 前碧蓝档案制作人主导全新手游计划Project K5预计9月1日公开 03-30
- 性感死神妹力四射 推理所剩无几但很涩的雾雨迷宫 03-30
- 绝区零月城柳怎么玩 电系异常核心极性紊乱爆发天花板 03-30
- 如何在QQ邮箱撤回邮件 03-30