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

运行结果

相关推荐
yue0082 小时前
C#理论学习-WinForm实践开发教程总结
开发语言·学习·c#
睡前要喝豆奶粉5 小时前
多表分页联查——EF Core方式和Dapper方式
c#·.netcore
格兰芬多呼神护卫6 小时前
python实现Latex格式的公式转OMML并写入word
python·c#·word
chao1898447 小时前
C 文件操作全解速览
服务器·c语言·c#
月巴月巴白勺合鸟月半9 小时前
一个DevExpress的Docx文件处理的Bug的解决
c#·bug
.NET修仙日记10 小时前
第一章:从零开始构建你的第一个C#/.NET应用程序
c#·.net·.net core
m5655bj17 小时前
如何使用 Python 转换 Excel 工作表到 PDF 文档
开发语言·c#·excel
技术支持者python,php18 小时前
SUB设备电子狗加密狗开发
c#
唐青枫19 小时前
循环插入太慢?试试 C#.NET SqlBulkCopy,一次导入上百万数据
c#·.net
SmoothSailingT1 天前
C#窗体—子窗体获取父窗体TextBox框的值
c#·窗体