C#中return的作用 | 您所在的位置:网站首页 › ret返回到哪里 › C#中return的作用 |
之前学过C#基础,里面简单都提及过方法中return的用法;在机房重构中做了实践,但没有怎么留意return的作用,今天自己就来简单总结一下return的作用。
1.在有返回值的方法中,return的作用是为这个方法返回一个值。 E.G: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { public class Program { static void Main(string[] args) { Class1 cl1 = new Class1();//实例化Class1类 int result = cl1.GetResult();//调用方法,将值传给变量result Console.WriteLine("result = " + result); Console.ReadKey(); } } public class Class1 { public int GetResult() { int result = 1; return result; } } }结果:result = 1
比喻:Main方法中的变量result就像是顾客,GetResult方法就像是快递驿站,上面的步骤就是驿站把快递给了顾客。
2.在不需要返回值的方法中(void),return的作用是结束该方法。 比如在一个Winform窗体中,我们要设置一个if语句判断textbox是否为空,但在这之后并没有写else语句,如果我们只在if语句中写“MessageBox.Show()”,就算出了错误程序还是会继续走下去,这时我们就需要在if括号内加上return。 |
CopyRight 2018-2019 实验室设备网 版权所有 |