C# break 和 return的区别
2022/8/22 1:26:26
本文主要是介绍C# break 和 return的区别,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
下面示例是break的用法:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Drawing; 6 using System.Windows.Forms; 7 8 namespace ReturnDemo 9 { 10 class Kodify_Example 11 { 12 static void Main() 13 { 14 for (int i = 1; i <= 7; i++) 15 { 16 17 for (int j = 1; j <= 7; j++) 18 { 19 int product = i * j; 20 21 if (product >= 20) 22 { 23 break; 24 } 25 Console.Write("{0}\t", product); 26 } 27 Console.WriteLine("\n"); 28 Console.Write("I am inner"); 29 Console.WriteLine("\n"); 30 } 31 Console.WriteLine("\nFinished with calculations."); 32 } 33 } 34 }
由上面示例可见,每次j循环达到break语句条件时,break只是跳出了最内部的循环,外部循环继续运行,i=1直到i=7全部循环完毕。
下面是return的用法:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Drawing; 6 using System.Windows.Forms; 7 8 namespace ReturnDemo 9 { 10 class Kodify_Example 11 { 12 static void Main() 13 { 14 for (int i = 1; i <= 7; i++) 15 { 16 17 for (int j = 1; j <= 7; j++) 18 { 19 int product = i * j; 20 21 if (product >= 20) 22 { 23 return; 24 } 25 Console.Write("{0}\t", product); 26 } 27 Console.WriteLine("\n"); 28 Console.Write("I am inner"); 29 Console.WriteLine("\n"); 30 } 31 Console.WriteLine("\nFinished with calculations."); 32 } 33 } 34 }
由上面示例可见,第一次达到触发returnt条件语句时,return就跳转到整个void Main()函数的外层,就连Console.WriteLine("\nFinished with calculations.");这条语句都没有显示出来。
综合上述:
break仅导致从循环退出,所以任何循环之后的语句都会执行。另一方面,return会导致从当前函数体中退出,所以函数体内的语句不会再执行。
所以,在触发语句之后你想要退出当前函数体,就用return;如果你想要继续在函数体中执行,使用break.
break
causes exit from the loop only, so any statements after loop will be executed. On the other hand, return
causes exit from the current function, so no further statements inside this function will be executed.
So - if you want to exit current function after finding the first element, use return
. If you want to continue execution in this function, use break
.
这篇关于C# break 和 return的区别的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具
- 2024-01-24.NET集成IdGenerator生成分布式全局唯一ID
- 2024-01-23用CI/CD工具Vela部署Elasticsearch + C# 如何使用
- 2024-01-23.NET开源的简单、快速、强大的前后端分离后台权限管理系统