更新於 2024/10/12閱讀時間約 7 分鐘

補充教學-陣列

    五種陣列使用方式

    ArraySample.aspx

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ArraySample.aspx.cs" Inherits="ArraySample" %>

    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    <br />
    <asp:Label ID="Label2" runat="server" Text=""></asp:Label>
    <br />
    <asp:Label ID="Label3" runat="server" Text=""></asp:Label>
    <br />
    <asp:Label ID="Label4" runat="server" Text=""></asp:Label>
    <br />
    <asp:Label ID="Label5" runat="server" Text=""></asp:Label>
    <br />
    <asp:Label ID="Label6" runat="server" Text=""></asp:Label>
    <br />
    </div>
    </form>
    </body>
    </html>

    ArraySample.aspx.cs

    protected void Page_Load(object sender, EventArgs e)
    {
    //五種陣列使用方式

    //1.宣告時同時初始化陣列(有預設值)
    int[] arr1 = new int[] { 1, 2, 3 };

    for(int i=0; i<arr1.Length; i++)
    {
    Label1.Text += $"sample1.1:陣列第{i}個元素,ary1[{i}] = {arr1[i]} <br>";
    }

    //或者可以省略 `new int[]`
    int[] arr2 = { 4, 5, 6 };

    for (int i = 0; i < arr2.Length; i++)
    {
    Label2.Text += $"sample1.2:陣列第{i}個元素,ary2[{i}] = {arr2[i]} <br>";
    }


    //2.宣告後再指定值
    int[] arr3 = new int[3];

    arr3[0] = 7;
    arr3[1] = 8;
    arr3[2] = 9;

    for (int i = 0; i < arr3.Length; i++)
    {
    Label3.Text += $"sample2:陣列第{i}個元素,ary3[{i}] = {arr3[i]} <br>";
    }

    //3.使用 Array 類別(class)
    Array arr4 = Array.CreateInstance(typeof(int), 3);
    arr4.SetValue(1, 0);
    arr4.SetValue(2, 1);
    arr4.SetValue(3, 2);

    for (int i = 0; i < arr3.Length; i++)
    {
    Label4.Text += $"sample3:陣列第{i}個元素,ary4[{i}] = {arr4.GetValue(i)} <br>";
    }

    //4.多維陣列宣告
    //宣告一個 2x2 的整數二維陣列並初始化
    int[,] arr5 = new int[2, 2] { { 1, 2 }, { 3, 4 } };

    //宣告一個 2x3 的整數二維陣列,但不賦值
    //int[,] ary5 = new int[2, 3];

    for(int i=0; i < arr5.GetLength(0); i++)
    {
    for(int j=0; j < arr5.GetLength(1); j++)
    {
    Label5.Text += $"sample4:arr5[{i}, {j}] = {arr5[i,j]} <br>";
    }
    }


    //5.不規則陣列(Jagged Array)
    int[][] arr6 = new int[2][];

    // 初始化子陣列
    arr6[0] = new int[] { 1, 2 };
    arr6[1] = new int[] { 3, 4, 5 };

    for (int i = 0; i < arr6.Length; i++) // 外層迴圈遍歷每個子陣列
    {
    for (int j = 0; j < arr6[i].Length; j++) // 內層迴圈遍歷每個子陣列的元素
    {
    Label6.Text += $"sample5:arr6[{i}][{j}] = {arr6[i][j]} <br>";
    }
    }
    }

    執行結果:




    分享至
    成為作者繼續創作的動力吧!
    © 2024 vocus All rights reserved.