數(shù)組是一種基本的數(shù)據(jù)結(jié)構(gòu),用于在單個變量下存儲固定大小的相同類型元素的順序集合。在 C# 中,數(shù)組是一種引用類型,可以用于存儲多個數(shù)據(jù)項。
理解數(shù)組
數(shù)組的定義
數(shù)組是一種數(shù)據(jù)結(jié)構(gòu),它可以存儲一系列相同類型的元素。在 C# 中,數(shù)組的索引從 0 開始。
數(shù)組的聲明
在 C# 中,聲明數(shù)組的語法如下:
dataType[] arrayName;
例如:
int[] numbers;
string[] names;
數(shù)組的初始化
數(shù)組的初始化可以在聲明時進行,也可以在聲明后進行。
int[] numbers = new int[5]; // 聲明一個包含5個整數(shù)的數(shù)組
string[] names = { "Alice", "Bob", "Charlie" }; // 聲明并初始化一個字符串數(shù)組
數(shù)組的訪問
訪問數(shù)組中的元素通過索引進行:
int firstNumber = numbers[0]; // 訪問第一個元素
string firstNames = names[0]; // 訪問第一個名字
數(shù)組的特點
固定大小
一旦數(shù)組被創(chuàng)建,它的大小就是固定的,不能增加或減少。
同類型元素
數(shù)組只能存儲同一數(shù)據(jù)類型的元素。
隨機訪問
數(shù)組支持通過索引隨機訪問元素,訪問速度快。
數(shù)組的應(yīng)用場景
數(shù)據(jù)集合
當你需要存儲一組相同類型的數(shù)據(jù)時,如學(xué)生的成績列表。
緩存機制
當你需要緩存數(shù)據(jù)以便快速訪問時,如圖像處理中的像素數(shù)據(jù)。
查找表
當你需要通過索引快速查找數(shù)據(jù)時,如鍵盤字符與其 ASCII 值的映射。
臨時存儲
當你需要臨時存儲數(shù)據(jù)進行處理時,如排序算法中的輔助數(shù)組。
數(shù)組的例子
基本數(shù)組操作
namespace App08
{
internal class Program
{
static void Main(string[] args)
{
// 聲明并初始化一個整數(shù)數(shù)組
int[] scores = newint[] { 90, 85, 80, 75, 70 };
// 遍歷數(shù)組
for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine(scores[i]);
}
// 使用 foreach 遍歷數(shù)組
foreach (int score in scores)
{
Console.WriteLine(score);
}
// 修改數(shù)組元素
scores[2] = 82;
// 多維數(shù)組
int[,] matrix = newint[3, 3] {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
// 遍歷二維數(shù)組
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
}
}
}
?
數(shù)組作為方法參數(shù)
namespace App08
{
internal class Program
{
static void Main(string[] args)
{
// 定義一個計算數(shù)組元素總和的方法
static int Sum(int[] arr)
{
int sum = 0;
foreach (int item in arr)
{
sum += item;
}
return sum;
}
// 調(diào)用方法
int[] numbers = { 1, 2, 3, 4, 5 };
int total = Sum(numbers);
Console.WriteLine("Total: " + total);
}
}
}

數(shù)組的排序和搜索
namespace App08
{
internal class Program
{
static void Main(string[] args)
{
// 排序數(shù)組
int[] nums = { 3, 1, 4, 1, 5, 9 };
Array.Sort(nums);
// 搜索數(shù)組
int index = Array.IndexOf(nums, 4);
Console.WriteLine("Index of 4: " + index);
}
}
}

總結(jié)
數(shù)組是 C# 中一種非常重要的數(shù)據(jù)結(jié)構(gòu),它提供了一種有效的方式來存儲和訪問一系列相同類型的數(shù)據(jù)。雖然數(shù)組具有固定大小的限制,但它們在許多編程情境中是不可或缺的,特別是在需要快速按索引訪問數(shù)據(jù)時。通過本課程的學(xué)習(xí),你應(yīng)該能夠理解數(shù)組的基本概念、特點和應(yīng)用場景,并能夠在 C# 程序中有效地使用數(shù)組。
閱讀原文:原文鏈接
該文章在 2025/3/24 17:21:01 編輯過