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 }