foreach循环

   foreach Loops
 A foreach loop allows you to address each element in an array using this simple syntax: foreach ( in ){ // can use for each element}This loop will cycle through each element, placing each one in the variable in turn, without danger of accessing illegal elements. You don't have to worry about how many elements there are in the array, and you can be sure that you'll get to use each one in the loop. Using this approach, you can modify the code in the last example as follows: static void Main(string[] args){ string[] friendNames = {"Robert Barwell", "Mike Parry", "Jeremy Beacock"}; Console.WriteLine("Here are {0} of my friends:", friendNames.Length);foreach (string friendName in friendNames){Console.WriteLine(friendName);} Console.ReadKey();}The output of this code will be exactly the same that of the previous Try It Out. The main difference between using this method and a standard for loop is that foreach gives you read- only access to the array contents, so you can't change the values of any of the elements. You couldn't, for example, do the following: foreach (string friendName in friendNames){friendName = "Rupert the bear";}If you try this, compilation will fail. If you use a simple for loop, however, you can assign values to array elements

你可能感兴趣的:(foreach循环)