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

运行结果

相关推荐
阿蒙Amon3 小时前
C# Linq to SQL:数据库编程的解决方案
数据库·c#·linq
iCxhust6 小时前
c# U盘映像生成工具
开发语言·单片机·c#
emplace_back7 小时前
C# 集合表达式和展开运算符 (..) 详解
开发语言·windows·c#
阿蒙Amon8 小时前
为什么 12 版仍封神?《C# 高级编程》:从.NET 5 到实战架构,进阶者绕不开的必修课
开发语言·c#
深海潜水员9 小时前
【Behavior Tree】-- 行为树AI逻辑实现- Unity 游戏引擎实现
游戏·unity·c#
开开心心_Every9 小时前
便捷的Office批量转PDF工具
开发语言·人工智能·r语言·pdf·c#·音视频·symfony
小码编匠11 小时前
C# 上位机开发怎么学?给自动化工程师的建议
后端·c#·.net
钢铁男儿11 小时前
C# 接口(什么是接口)
java·数据库·c#
小老鼠爱大米15 小时前
C# WPF - Prism 学习篇:搭建项目(一)
c#·wpf·prism