在 C# 中獲取陣列的大小
本教程將討論在 C# 中獲取陣列大小的方法。
使用 C# 中的 Array.Length 屬性獲取陣列的大小
陣列的大小表示陣列可以儲存在其中的元素總數。Array.Length 屬性提供了 C# 中陣列的總大小。下面的程式碼示例向我們展示瞭如何使用 C# 中的 Array.Length 屬性獲取陣列的長度。
using System;
namespace size_of_array {
class Program {
static void method1() {
int[] a = new int[17];
Console.WriteLine(a.Length);
}
static void Main(string[] args) {
method1();
}
}
}
輸出:
17
在上面的程式碼中,我們使用 C# 中的 a.Length 屬性獲得 a 陣列的長度。此方法還可用於獲取多維陣列的總大小。下面給出確定二維陣列總大小的程式碼。
using System;
namespace size_of_array {
class Program {
static void method1() {
int[,] a = new int[17, 2];
Console.WriteLine(a.Length);
}
static void Main(string[] args) {
method1();
}
}
}
輸出:
34
使用 C# 中的 Array.Rank 屬性和 Array.GetLength() 函式獲取多維陣列每個維度的大小
假設我們有一個多維陣列,我們想在多維陣列中獲取每個維的大小。在這種情況下,我們必須使用 Array.Rank 屬性和 C# 中的 Array.GetLength() 函式。Array.Rank 屬性為我們提供了陣列內部的維數。Array.GetLength(i) 函式為我們提供了陣列 i 維的大小。下面的程式碼示例向我們展示瞭如何使用 C# 中的 Array.Rank 屬性和 Array.GetLength() 函式獲得多維陣列每個維度的總大小。
using System;
namespace size_of_array {
class Program {
static void method2() {
int[,] a = new int[17, 2];
int i = a.Rank;
for (int x = 0; x < i; x++) {
Console.WriteLine(a.GetLength(x));
}
}
static void Main(string[] args) {
method2();
}
}
}
輸出:
17
2
在上面的程式碼中,我們使用 a.Rank 屬性和 a.GetLength(x) 函式列印多維陣列 a 的每個維度的大小。我們使用 a.Rank 屬性獲取 a 陣列中的維數,並使用 for 迴圈遍歷每個維。然後,使用 a.GetLength(x) 函式列印每個維度的大小,其中 x 是該維度的索引。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn