在 C# 中,如何取得 string[] str 陣列的元素個數?
直接使用 Length 屬性:
int count = str.Length;
Length 是陣列的唯讀屬性,回傳所有維度的元素總數(一維陣列即為元素個數)。Count() 擴充方法混淆,後者屬於 LINQ,需引用 System.Linq 且為方法呼叫,效能稍差。string[] fruits = { "Apple", "Banana", "Cherry" };
Console.WriteLine($"陣列長度: {fruits.Length}"); // 輸出 3
// 錯誤寫法示範
// int len = fruits.Count; // 編譯錯誤:Count 是方法而非屬性
// int len = fruits.Count(); // 可行但多引用 LINQ
記住:陣列用 .Length,集合(List、ArrayList 等)用 .Count 屬性或 .Count() 方法。