C# - 数组

本文关键字:数组 | 更新日期: 2023-09-12 17:39:12

变量用于存储文本值,而数组用于存储多个文本值。

数组是存储相同数据类型)的固定数量的文字值(元素)的数据结构。数组元素连续存储在内存中。

在 C# 中,数组可以是三种类型:一维数组、多维数组和交错数组。在这里,您将了解一维数组。

下图说明了数组表示形式。

数组表示

数组声明和初始化

数组可以通过用方括号指定数组元素的类型来声明。

Example: Array Declaration

int[] evenNums;  // integer array
string[] cities; // string array

下面在单个语句中声明值并将其添加到数组中。

Example: Array Declaration & Initialization

int[] evenNums = new int[5]{ 2, 4, 6, 8, 10 }; 
string[] cities = new string[3]{ "Mumbai", "London", "New York" };

上面evenNums数组最多可以存储五个整数。方括号中的数字 5 new int[5]指定数组的大小。 同样,cities数组的大小为三。数组元素添加到大括号 { } 内的逗号分隔列表中。

数组类型变量可以使用var 不带方括号来声明。

Example: Array Declaration using var

var evenNums = new int[]{ 2, 4, 6, 8, 10}; 
var cities = new string[]{ "Mumbai", "London", "New York" }; 

如果在声明时添加数组元素,则大小是可选的。编译器将根据大括号内的元素数推断其大小,如下所示。

Example: Short Syntax of Array Declaration

int[] evenNums = { 2, 4, 6, 8, 10}; 
string[] cities = { "Mumbai", "London", "New York" }

下面的示例演示无效的数组声明。

Example: Invalid Array Creation

//must specify the size 
int[] evenNums = new int[]; 
//number of elements must be equal to the specified size 
int[] evenNums = new int[5] { 2, 4 };
//cannot use var with array initializer
var evenNums = { 2, 4, 6, 8, 10}; 

延迟初始化

不必在单个语句中声明和初始化数组。您可以先声明一个数组,然后使用 new 运算符对其进行初始化。

Example: Late Initialization

int[] evenNums;
evenNums = new int[5];
// or
evenNums = new int[]{ 2, 4, 6, 8, 10 };

访问数组元素

可以使用索引访问数组元素。索引是与每个数组元素关联的数字,从索引 0 开始,以数组大小 - 1 结束。

下面的示例使用索引添加/更新和检索数组元素。

Example: Access Array Elements using Indexes

int[] evenNums = new int[5];
evenNums[0] = 2;
evenNums[1] = 4;
//evenNums[6] = 12;  //Throws run-time exception IndexOutOfRange
Console.WriteLine(evenNums[0]);  //prints 2
Console.WriteLine(evenNums[1]);  //prints 4

请注意,尝试添加的元素数超过其指定大小将导致IndexOutOfRangeException

使用 for 循环访问数组

使用 for 循环访问数组元素。在 for 循环的条件表达式中使用数组的 length 属性。

Example: Accessing Array Elements using for Loop

int[] evenNums = { 2, 4, 6, 8, 10 };
for(int i = 0; i < evenNums.Length; i++)
            Console.WriteLine(evenNums[i]);  
for(int i = 0; i < evenNums.Length; i++)
    evenNums[i] = evenNums[i] + 10;  // update the value of each element by 10

使用 foreach 循环访问数组

使用循环foreach读取数组元素的值,而无需使用索引。

Example: Accessing Array using foreach Loop

int[] evenNums = { 2, 4, 6, 8, 10}; 
string[] cities = { "Mumbai", "London", "New York" }; 
foreach(var item in evenNums)
            Console.WriteLine(item);   
foreach(var city in cities)
            Console.WriteLine(city);  

LINQ 方法

C# 中的所有数组都派生自抽象基类System.Array。

Array 类实现了IEnumerable接口,因此可以 LINQ 扩展方法,如 Max()Min()Sum()reverse() 等。 请参阅所有扩展方法的列表here.

Example: LINQ Methods

int[] nums = new int[5]{ 10, 15, 16, 8, 6 };
nums.Max(); // returns 16
nums.Min(); // returns 6
nums.Sum(); // returns 55
nums.Average(); // returns 55

System.Array类还包括用于创建、操作、搜索和排序数组的方法。 请参阅所有数组方法的列表here.

Example: Array Methods

int[] nums = new int[5]{ 10, 15, 16, 8, 6 };
Array.Sort(nums); // sorts array 
Array.Reverse(nums); // sorts array in descending order
Array.ForEach(nums, n => Console.WriteLine(n)); // iterates array
Array.BinarySearch(nums, 5);// binary search 

将数组作为参数传递

数组可以作为参数传递给方法参数。数组是引用类型,因此该方法可以更改数组元素的值。

Example: Passing Array as Argument

public static void Main(){
            int[] nums = { 1, 2, 3, 4, 5 };
    UpdateArray(nums); 
            foreach(var item in nums)
            Console.WriteLine(item);   
}
                    
public static void UpdateArray(int[] arr)
{
            for(int i = 0; i < arr.Length; i++)
        arr[i] = arr[i] + 10;   
}