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

运行结果

相关推荐
夏子曦15 小时前
C#内存管理深度解析:从栈堆原理到高性能编程实践
开发语言·c#
William_cl19 小时前
C# MVC网页调试的方法
开发语言·c#·mvc
小小的技术员19 小时前
C# 无实体生成JSON字符串
c#·json
L X..1 天前
Unity反射调用 ReactiveProperty<T>(泛型类型)内部方法时崩溃
unity·c#·游戏引擎·.net
缺点内向1 天前
C# 中 Excel 工作表打印前页面边距的设置方法
c#·.net·excel
雪芽蓝域zzs2 天前
uniapp AES 加密解密
开发语言·uni-app·c#
weixin_456904272 天前
C# 中的回调函数
java·前端·c#
千忧散2 天前
Unity Socket学习笔记 (三)TCP&UDP
笔记·学习·unity·c#
君莫愁。2 天前
【Unity】构建超实用的有限状态机管理类
unity·c#·游戏引擎·有限状态机
WangMing_X2 天前
《使用模块化分层来达到企业级项目要求》
开发语言·c#