C#学习笔记:C#中的四种循环⽅式(原理+代码)作者信息:Richard Tian (from the University of Sydney) 码字不易,转载请注明出处和作者联系⽅式(如下)即可。
Github:
LinkedIn:
Zhihu:
假设现有⼀个 array,我们希望能够遍历它之中的每⼀个元素。在 C# 中,⼀共有四种循环语句可以帮助我们达成这个⽬的。为⽅便演⽰,我们⾸先初始化⼀个具有五个元素的 string array。
// At first we'd better to initiate a sample array
// in order to demonstrate well
var sampleArray = new string[5] { "Mike", "Amy", "Josh", "Mark", "Daneil" };
1. For Loop
最经典的循环结构,与 C 和 C++完全相同。
writeline使用方法python// for loop
Console.WriteLine("For Loop:");
Console.WriteLine("Ps: The Length of an array can be found by: array.Length");
for (int i = 0; i < sampleArray.Length; i++)
{
Console.WriteLine(sampleArray[i]);
}
2. Foreach
有点类似于 Python 的循环结构。
// foreach loop
Console.WriteLine("Foreach Loop:");
Console.WriteLine("Ps: This method is most likely to Python iteration");
foreach (var element in sampleArray)
{
Console.WriteLine(element);
}
3. While
别忘记每次 While 内代码段执⾏后需要将 i++
// while loop
Console.WriteLine("While Loop:");
int j = 0;
while (j < sampleArray.Length)
{
Console.WriteLine(sampleArray[j]);
j++;
}
4. Do-while
和 While 的最⼤区别就是 Do-while 会先执⾏⼀次再进⾏条件判断。
// do-while loop
Console.WriteLine("Do-while Loop:");
Console.WriteLine("Ps: The workflow would be executed at least 1 time");
int k = 0;
do
{
Console.WriteLine(sampleArray[k]);
k++;
} while (k < sampleArray.Length);
PS:break 与 continue
在循环中,break 将会引导⼯作流跳出整个循环;⽽ continue 只会让⼯作流跳出这次迭代并开始下⼀次迭代。注意这两段代码输出时的区别。
// break
// jumps out of the whole loop
Console.WriteLine("Function of break:");
foreach (var element in sampleArray)
{
if (element == "Amy")
break;
else
Console.WriteLine(element);
}
// continue
// jumps out of this iteration and start the next one
Console.WriteLine("Function of continue:");
foreach (var element in sampleArray)
{
if (element == "Amy")
continue;
else
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。