![](/img/trans.png)
[英]More elements in LinkedList<T> than COUNT property can return in C#
[英]I just can't insert more than 5 elements in a array in C#
我正在嘗試制作一個簡單的程序,在其中我用一個輸入聲明數組的大小,但是如果數組有 5 個以上的元素,我會給出一個 IndexOutOfRange 異常。 有人可以幫我理解為什么嗎?
class Program
{
static void Main(string[] args)
{
int[] array = new int[5];
Console.WriteLine("Declare the array size");// 6
int quant = int.Parse(Console.ReadLine());
for (int i = 0; i < quant; i++) {
Console.WriteLine("Fill in the {0}º value ", i+1);
int number = int.Parse(Console.ReadLine());
array[i] = number;
}
for (int i=0; i< quant; i++)
{
Console.WriteLine("\n", array[i]);
}
}
}
在讀取用戶的輸入后,您需要創建一個數組來指定元素的數量。 您在代碼中所做的是創建一個大小為 5 的 int 數組。如果用戶寫入的數字大於 5,您將收到 IndexOutOfRange 異常。
class Program
{
static void Main(string[] args)
{
int quant = int.Parse(Console.ReadLine());
int[] array = new int[quant ];
for (int i = 0; i < quant; i++){
Console.WriteLine("Fill in the {0}º value ", i+1);
int number = int.Parse(Console.ReadLine());
array[i] = number;
}
for (int i=0; i< quant; i++){
Console.WriteLine("\n", array[i]);
}
}
}
如果您想在不指定固定限制的情況下使用數組,則在 C# 中是不可能的(例如在 JS 中)。 您可以在 C# 中使用稱為List
的不同類型實現此要求,該類型表示可以通過索引訪問的強類型對象列表,並且不需要在初始化時指定固定大小(與數組相反)
閱讀有關列表的更多信息 - https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-5.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.