return; 直接作为一条语句表示当前函数(也可以叫做方法)结束
return后有东西,则是返回和函数返回类型一致的对象
例如:return 1;表示语句跳转到函数末尾 并且返回值为1
具体:
平时用的时候主要用在结束循环啦。。返回个方法的值啦。。之类的。给你写个小例子。
结束循环:
1 int a; 2 for ( int i = 0 ; i < 9 ; i ++ ) 3 { 4 if( i == 4) 5 { 6 a = i; 7 return; //这时候。当I等于4的时候。遁环就结束了。执行循环下面的语句。 8 } 9 } 10 a = a + 250 - a ; //猜猜这个值是多少~~(这个是恶搞)
返回值的例子:
1 public void math( int a ) 2 { 3 int b; 4 b = a * 2 ; 5 return b; //这时候就是把B的值返回给调用这个方法的地方,比如调用的时候是这样的 6 }
调用:
7 int c; 8 c = math(4); //这样会把4转到方法里面,在方法里面算出4的倍数,再把算好的值传回C ,所以C的结果是 8 。
方法、do while、try catch、return混合使用:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace ReadInt方法 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 Console.WriteLine("请输入你的年龄?"); 14 int age = ReadInt();//调用ReadInt方法并赋值给age 15 Console.WriteLine("你刚刚输入的年龄为"+age); 16 17 Console.WriteLine("请输入你是哪一年出生的?"); 18 int year = ReadInt();//调用ReadInt方法并赋值给year 19 Console.WriteLine("噢,你是{0}年出生的呀!" ,year); 20 21 Console.WriteLine("请输入你们班有多少人?"); 22 int count = ReadInt();//调用ReadInt方法并赋值给count 23 Console.WriteLine("你们班有{0}人", count); 24 25 Console.ReadKey();//等待 26 } 27 public static int ReadInt()//创建ReadInt方法 28 { 29 int number = 0; 30 do 31 { 32 try 33 { 34 number = Convert.ToInt32(Console.ReadLine());//得到输入的字符并转化成整数 35 return number;//退出循环并返回整数值 36 } 37 catch 38 { 39 Console.WriteLine("输入有误,请重新输入!"); 40 } 41 } 42 while(true); 43 } 44 } 45 }