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();
        }
    }
}

运行结果

相关推荐
小码编匠6 小时前
WPF 中的高级交互通过右键拖动实现图像灵活缩放
后端·c#·.net
唐青枫13 小时前
C#.NET 定时任务与队列利器:Hangfire 完整教程
c#·.net
hez201019 小时前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
mudtools1 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫1 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
唐青枫2 天前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
未来之窗软件服务3 天前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
1uther3 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎