C# 数组(Array)

C# 数组(Array)

初始化数组

声明一个数组不会在内存中初始化数组。当初始化数组变量时,您可以赋值给数组。

数组是一个引用类型,所以您需要使用 new 关键字来创建数组的实例。

例如:

csharp 复制代码
double[] b = new double[10];

赋值给数组

您可以通过使用索引号赋值给一个单独的数组元素,比如:

csharp 复制代码
double[] b = new double[10];
b[0] = 100;

您可以在声明数组的同时给数组赋值,比如:

csharp 复制代码
double[] a = { 12, 1, 3};

您也可以创建并初始化一个数组,比如:

csharp 复制代码
int [] c = new int[5]  { 1,  2, 3, 7, 5};

在上述情况下,你也可以省略数组的大小,比如:

csharp 复制代码
int [] d = new int[]  { 1,  2, 3, 4, 9};

您也可以赋值一个数组变量到另一个目标数组变量中。在这种情况下,目标和源会指向相同的内存位置:

csharp 复制代码
int [] e = new int[]  { 1,  2, 92, 97, 95};
int[] f = e;

当您创建一个数组时,C# 编译器会根据数组类型隐式初始化每个数组元素为一个默认值。例如,int 数组的所有元素都会被初始化为 0。

访问数组元素

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Test
    {
        static void Main(string[] args)
        {
            int[] n = new int[10];
            int i, j;
            /* 初始化数组 n 中的元素 */
            for (i = 0; i < 10; i++)
            {
                n[i] = i + 100;
            }
            /* 输出每个数组元素的值 */
            for (j = 0; j < 10; j++)
            {
                Console.WriteLine("n[{0}] = {1}", j, n[j]);
            }
            Console.ReadKey();
        }
    }
}

运行结果

使用 foreach 循环

在前面的实例中,我们使用一个 for 循环来访问每个数组元素,您也可以使用一个 foreach 语句来遍历数组。

以下实例我们使用 foreach 来遍历一个数组:

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Test
    {
        static void Main(string[] args)
        {
            int[] n = new int[10];
            /* 初始化数组 n 中的元素 */
            for (int i = 0; i < 10; i++)
            {
                n[i] = i + 100;
            }
            /* 输出每个数组元素的值 */
            foreach(int j in n)
            {
                int i = j - 100;
                Console.WriteLine("n[{0}] = {1}", i, j);
            }
            Console.ReadKey();
        }
    }
}

运行结果

相关推荐
i橡皮擦17 小时前
TheIsle恐龙岛读取游戏基址做插件(C#语言)
开发语言·游戏·c#·恐龙岛·theisle
用户21991679703911 天前
C# 14 中的新增功能
c#
垂葛酒肝汤1 天前
放置挂机游戏的离线和在线收益unity实现
游戏·unity·c#
爱说实话1 天前
C# 20260112
开发语言·c#
无风听海1 天前
C#中实现类的值相等时需要保留null==null为true的语义
开发语言·c#
云草桑1 天前
海外运单核心泡货计费术语:不计泡、计全泡、比例分泡
c#·asp.net·net·计泡·海运
精神小伙就是猛1 天前
C# Task/ThreadPool async/await对比Golang GMP
开发语言·golang·c#
工程师0071 天前
C#状态机
开发语言·c#·状态模式·状态机