简体   繁体   English

以下C#代码中的“ -1”是什么意思?

[英]What is the meaning of “-1” in the following C# code?

Hey guys I'm just starting to learn C# and I was wondering what the "-1" in the for loop meant? 大家好,我刚刚开始学习C#,我想知道for循环中的“ -1”是什么意思?

string[] fruit = { "Apples", "Oranges", "Grapes" };
for (int i = fruit.Length - 1; i >= 0; i--)
{
    // Code Here
    Console.WriteLine(fruit[i]);
}

I was trying to figure out how to go backwards in an array and I was able to do it, but I just want to know how the "-1" works in the for loop. 我试图弄清楚如何在数组中向后移动,但能够做到这一点,但是我只想知道“ -1”在for循环中的工作方式。 Why is it necessary? 为什么有必要?

Arrays in C# are 0-indexed, meaning they begin at element [0]. C#中的数组从0开始索引,这意味着它们从元素[0]开始。 Thus, the largest accessible index is Length-1. 因此,最大的可访问索引是Length-1。

Length of array - 1 is to normalize it. 数组的长度-1是将其标准化。 Array starts at 0, while obviously counting numbers starts at 1. So the length of the array (or collection, semantics) - 1 would be the way to access the current index of the collection. 数组从0开始,而显然数字从1开始。因此,数组的长度(或集合,语义)-1是访问集合当前索引的方式。

An array starts indexing at 0 to array.length - 1 always and array length is going from 1 2 3..... to array.length, wich means fruit[0] fruit[1]....fruit[fruit.length -1] and that is the last element. 数组从0开始索引到array.length-始终为1,数组长度从1 2 3 .....到array.length,其中wich表示fruit [0] fruit [1] .... fruit [fruit。 -1),这是最后一个元素。 So you are starting a reverse loop, from fruit[fruit.length - 1]...... to fruit[0], if you put fruit[fruit.length] you will get indexOutOfBoundsException. 因此,您将开始一个反向循环,从fruit [fruit.length-1] ......到fruit [0],如果您将fruit [fruit.length]放入,则会得到indexOutOfBoundsException。 Debugging your app is the best way to see what's happening. 调试应用程序是了解正在发生的事情的最佳方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM