编程初学者有时候搞不清楚一些常用关键词的特性,这里就用几个代码片段解释一下break、continue、return各自的特性。
我把整个文件都粘上来了,但其中主要的就是Main函数里面的那些,1、2、3、4已用空格分开,测试的时候分别解注释运行就好了。(注:我用的环境是VS2017,C#语言,控制台应用测试,但for循环几乎是所有编程语言通用的。如果你用的是其他开发环境,可以完全无视那些引入命名空间,只把几个for循环粘出去测试就好了)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//1、break的特性
for (int i = 1; i <= 10; i++)
{
if (i % 4 == 0)
{
break;
}
Console.WriteLine(i);
}
//2、continue的特性
//for (int i = 1; i < 11; i++)
//{
// if (i % 4 == 0)
// {
// continue;
// }
// Console.WriteLine(i);
//}
/*
【体会break和continue的区别:break跳出for循环体,不再循环,而是执行for循环后面的语句。
continue结束此次循环,继续下次的for循环(比如:
这次循环的i变量为3,则不再执行for循环内continue后面的语句,而是执行当i为4时候的for循环内所有语句,
除非有其他的判断条件导致再次执行continue功能)。
】
*/
//3、附加,同时对比continue和break
//int[] number = new int[] { 1, 2, 3, 4, 5 };
//foreach (int s in number)
//{
// if (s == 3)
// {
// continue;
// }
// if (s == 5)
// {
// break;
// }
// Console.WriteLine(s);
//}
//4、return的特性:
for (int i = 1; i <= 10; i++)
{
if (i % 4 == 0)
{
//Console.ReadLine();
/*如果不加这句读等待,程序会瞬间结束,看不到结果,所以就加上,让程序等待一下,
然后随意按下一个键就可以感觉到return的效果了:程序将不再往下进行。*/
return;
}
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}