C#定义数组的四种方式(推荐前两种,因为方便、好写)

第一种:

 int[] nums = new int[10];

举例:

using System;

namespace 定义数组的四种方式
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] nums = new int[10];
            for (int i = 0; i < nums.Length; i++)
            {
                nums[i] = i;
            }
            for (int i = 0; i < nums.Length; i++)
            {
                Console.WriteLine(nums[i]);
            }
            Console.ReadKey();
        }
    }
}

在这里插入图片描述

第二种:

int[] numsTwo = { 1, 2, 3, 4, 5, 6 };

举例:

using System;

namespace 定义数组的四种方式
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numsTwo = { 1, 2, 3, 4, 5, 6 };
            for(int i=0;i<numsTwo.Length;i++)
            {
                numsTwo[i] = i;
            }
            for (int i = 0; i < numsTwo.Length; i++)
            {
                Console.WriteLine(numsTwo[i]);
            }
            Console.ReadKey();
        }
    }
}

在这里插入图片描述

第三种:

int[] numsThree = new int[3] { 1, 2, 3 };

举例:

using System;

namespace 定义数组的四种方式
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numsThree = new int[3] { 1, 2, 3 };
            for (int i = 0; i < numsThree.Length; i++)
            {
                numsThree[i] = i;
            }
            for (int i = 0; i < numsThree.Length; i++)
            {
                Console.WriteLine(numsThree[i]);
            }
            Console.ReadKey();
        }
    }
}

在这里插入图片描述

第四种:

int[] numsFour = new int[] { 1, 2, 3,4,5 };

举例:

using System;

namespace 定义数组的四种方式
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numsFour = new int[] { 1, 2, 3,4,5 };
            for (int i = 0; i < numsFour.Length; i++)
            {
                numsFour[i] = i;
            }
            for (int i = 0; i < numsFour.Length; i++)
            {
                Console.WriteLine(numsFour[i]);
            }
            Console.ReadKey();
        }
    }
}

在这里插入图片描述


版权声明:本文为AKK188888881原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。