zoukankan      html  css  js  c++  java
  • C# 数组的讲解(ArrayList 与List的区别)

    // 数组 有序的同元素的 缺点长度是固定的
    
    #region 类型数组
    //第一种方式 
    string[] str = new string[] { "a", "b", "c" };
    //第二种方式
    string[] str1 = new string[3];
    str1[0] = "a";
    
    str1[1] = "b";
    
    str1[2] = "c";
    
    //第三种方式
    string[] str2 = { "a", "b" ,"c"};
    #endregion
    
     
    
    //对象数组(两种声明方式)
    Student s1 = new Student();
    s1.Age = 34;
    s1.Name = "李四";
    
    Student s2 = new Student();
    s2.Age = 16;
    s2.Name = "wangwu";
    //方法一
    Student[] student = new Student[2];
    student[0] = s1;
    student[1] = s2;
    
    //方法二
    Student[] studentTest = new Student[] {
      new Student { Name="asd",Age=23},
      new Student { Name="ew",Age=34}
    };
    
     
    
    //ArrayList 有序的数组,元素是object,
    //优点:长度不固定,缺点:进行类型的隐式转换,耗费系统的资源
    ArrayList ary = new ArrayList();
    ary.Add("asdf");
    ary.Add(23);
    ary.Add("asec");
    for (int i = 0; i < ary.Count; i++)
    {
      Console.WriteLine(ary[i] +"的类型为:"+ ary[i].GetType());
    }
    //根据元素移除,RemoveAt(index) 根据下标移除
    ary.Remove(23);
    
    Console.WriteLine("-----------------------Hashtable----------------------------");
    
    //Hashtable无需的数组,有键值对(键必须唯一),元素是object,
    //优点:长度不固定,缺点:进行类型的隐式转换,耗费系统的资源
    Hashtable ht = new Hashtable();
    ht.Add("a","值得");
    ht.Add("b", "dec");
    ht.Add("c", "cere");
    
    //根据键移除元素
    ht.Remove("a");
    
    //遍历的key,获取对应的value值
    foreach (var item in ht.Keys)
    {
    Console.WriteLine("key:"+item+",value:"+ht[item]);
    }
    
    //List 有序的数组,元素对象明确的类型,优点长度不固定,不需要进行类型转换,对ArrayList的升级
    List<Student> lst = new List<Student>();
    lst.Add(s1);
    lst.Add(s2);
    lst.Remove(s2);
    
    //Dictionary 无序的数组,对Hashtable的升级
    Dictionary<string, Student> dic = new Dictionary<string, Student>();
    dic.Add("da",s1);
    dic.Add("dw",s2);
    
    //第一种
    foreach (var item in dic.Keys)
    {
    Console.WriteLine("key:" + item + ",value:" + dic[item].Name);
    }
    
    //第二种(推荐的)
    foreach (KeyValuePair<string, Student> item in dic)
    {
    Console.WriteLine("key:" + item.Key + ",value:" + item.Value.Name);
    }
    
    综上所述:List 和 Dictionary 对 ArrayList 和 Hashtable 的升级。
  • 相关阅读:
    Linux每日一题——(2)vi文本编辑器
    Oracle每日一题——(1) 启动/停止监听
    Linux每日一题——(1)创建和删除用户
    Oracle实践:00600[4193]错误导致服务频繁宕掉问题
    在AX中生成二维码
    AX向在线用户发送消息
    TimeNow()获取时间与当前时间不符
    Changecompany中使用Box,Info等客户端方法后出错
    AX4.0删除引用
    poj1010解题报告
  • 原文地址:https://www.cnblogs.com/yang12311/p/10496926.html
Copyright © 2011-2022 走看看