zoukankan      html  css  js  c++  java
  • C#数组之 []、List、Array、ArrayList应用

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Collections;

    public partial class _Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    // System.Int32 是结构
    int[] arr = new int[] { 1, 2, 3 };
    Response.Write(arr[0]); // 1
    Change(arr);
    Response.Write(arr[0]); // 2

    // List 的命名空间是 System.Collections.Generic
    List<int> list = new List<int>();
    list.Add(1);
    list.Add(2);
    list.Add(3);
    Response.Write(list[0]); // 1
    Change(list);
    Response.Write(list[0]); // 2

    // Array 的命名空间是 System
    Array array = Array.CreateInstance(System.Type.GetType("System.Int32"), 3); // Array 是抽象类,不能使用 new Array 创建。
    array.SetValue(1, 0);
    array.SetValue(2, 1);
    array.SetValue(3, 2);
    Response.Write(array.GetValue(0)); // 1
    Change(array);
    Response.Write(array.GetValue(0)); // 2

    // ArrayList 的命名空间是 System.Collectio(www.111cn.net)ns
    ArrayList arrayList = new ArrayList(3);
    arrayList.Add(1);
    arrayList.Add(2);
    arrayList.Add(3);
    Response.Write(arrayList[0]); // 1
    Change(arrayList);
    Response.Write(arrayList[0]); // 2
    }

    private void Change(int[] arr)
    {
    for (int i = 0; i < arr.Length; i++)
    {
    arr[i] *= 2;
    }
    }

    private void Change(List<int> list)
    {
    for (int i = 0; i < list.Count; i++) // 使用 Count
    {
    list[i] *= 2;
    }
    }


    private void Change(Array array)
    {
    for (int i = 0; i < array.Length; i++) // 使用 Length
    {
    array.SetValue((int)array.GetValue(i) * 2, i); // 需要类型转换
    }
    }

    private void Change(ArrayList arrayList)
    {
    for (int i = 0; i < arrayList.Count; i++) // 使用 Count
    {
    arrayList[i] = (int)arrayList[i] * 2; // 需要类型转换
    }
    }
    }

    [] 是针对特定类型、固定长度的。

    List 是针对特定类型、任意长度的。

    Array 是针对任意类型、固定长度的。

    ArrayList 是针对任意类型、任意长度的。

    Array 和 ArrayList 是通过存储 object 实现任意类型的,所以使用时要转换
    from:http://www.111cn.net/net/160/40651.htm

  • 相关阅读:
    vscode source control provider not registered
    MAC NVM 安装
    《高效前端:Web 高效编程与优化实践》学习笔记
    回显服务端/client
    图像处理系列(1):測地线动态轮廓(geodesic active contour)
    Pro Android学习笔记(一三八):Home Screen Widgets(4):App Widget Provider
    怎样传输SE63的翻译内容
    <html>
    概率dp sgu495
    Android Afinal框架学习(一) FinalDb 数据库操作
  • 原文地址:https://www.cnblogs.com/alibai/p/4017863.html
Copyright © 2011-2022 走看看