Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C# 数组


创建数组

数组用于在单个变量中存储多个值,而不是为每个值声明单独的变量。

要声明数组,请使用 **方括号** 定义变量类型

string[] cars;

我们现在已经声明了一个保存字符串数组的变量。

要插入值,我们可以使用数组字面量 - 将值放在逗号分隔的列表中,放在花括号内

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

要创建整数数组,您可以编写

int[] myNum = {10, 20, 30, 40};

访问数组元素

您可以通过引用索引号来访问数组元素。

此语句访问 **cars** 中第一个元素的值

示例

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars[0]);
// Outputs Volvo

动手尝试 »

注意: 数组索引从 0 开始: [0] 是第一个元素。 [1] 是第二个元素,依此类推。



更改数组元素

要更改特定元素的值,请引用索引号

示例

cars[0] = "Opel";

示例

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
Console.WriteLine(cars[0]);
// Now outputs Opel instead of Volvo

动手尝试 »


数组长度

要找出数组有多少个元素,请使用 Length 属性

示例

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars.Length);
// Outputs 4

动手尝试 »


其他创建数组的方法

如果您熟悉 C#,您可能已经看到过使用 new 关键字创建的数组,也许您还看到过指定大小的数组。在 C# 中,有不同的方法可以创建数组

// Create an array of four elements, and add values later
string[] cars = new string[4];

// Create an array of four elements and add values right away 
string[] cars = new string[4] {"Volvo", "BMW", "Ford", "Mazda"};

// Create an array of four elements without specifying the size 
string[] cars = new string[] {"Volvo", "BMW", "Ford", "Mazda"};

// Create an array of four elements, omitting the new keyword, and without specifying the size
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

您选择哪个选项都可以。在本教程中,我们经常使用最后一个选项,因为它更快且更容易阅读。

但是,您应该注意,如果您声明数组并在以后初始化它,则必须使用 new 关键字

// Declare an array
string[] cars;

// Add values, using new
cars = new string[] {"Volvo", "BMW", "Ford"};

// Add values without using new (this will cause an error) cars = {"Volvo", "BMW", "Ford"};

动手尝试 »


C# 练习

通过练习测试自己

练习

创建一个类型为 string 且名为 cars 的数组。

  = {"Volvo", "BMW", "Ford", "Mazda"};

开始练习


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.