標籤:
---------------函數---------------
參數數組:可指定一個特定的參數,必須是最後一個參數,可使用個數不定的參數調用函數,用params關鍵字定義它們
例如:
1 static int SumVals(params int[] vals)2 {3 int sum = 0;4 foreach(int val in vals)5 {6 sum += val;7 }8 return sum;9 }
調用SumVals: int sum = SumVals(1,2,5,7,8,12,34);
結果sum=69
引用參數:關鍵字ref,傳遞參數本身而非傳遞參數的值
例如:
1 static void ShowDouble(ref int val)2 {3 val *= 2;4 }5 int i = 5;6 ShowDouble(ref i);
結果i=10
輸出參數:關鍵字out,傳出參數
例如:
1 static int MaxValue(int[] intArray,out int maxIndex) 2 { 3 int maxVal = intArray[0]; 4 maxIndex = 0; 5 for (int i = 0; i < intArray.Length; i++) 6 { 7 if (intArray[i] > maxVal) 8 { 9 maxIndex = i;10 maxVal = intArray[i];11 }12 }13 return maxVal;14 }
調用MaxValue:
1 int[] intArray = {1,2,5,7,8,12,34};2 int maxIndex,maxValue;3 maxValue = MaxValue(intArray,out maxIndex)
結果maxIndex = 6
委託執行個體:
1 class Program 2 { 3 delegate double ProcessDelegate(double param1, double param2); 4 5 static double Multiply(double param1, double param2) 6 { 7 return param1 * param2; 8 } 9 static double Divide(double param1, double param2)10 {11 return param1 / param2;12 }13 14 static void Main(string[] args)15 {16 ProcessDelegate process;17 Console.WriteLine("2 number");18 string input = Console.ReadLine();19 int commaPos = input.IndexOf(‘,‘);20 double param1 = Convert.ToDouble(input.Substring(0, commaPos));21 double param2 = Convert.ToDouble(input.Substring(commaPos + 1, input.Length - commaPos - 1));22 Console.WriteLine("xxx");23 input = Console.ReadLine();24 if (input == "M")25 process = new ProcessDelegate(Multiply);26 else27 process = new ProcessDelegate(Divide);28 Console.WriteLine("Result: {0}", process(param1, param2));29 Console.ReadKey();30 }31 }
---------------調試和錯誤處理---------------
斷點可選擇性觸發,列表如下:
1)總是中斷
2)在Hit Count等於多少次時中斷
3)在Hit Count是某個數的倍數時中斷
4)在Hit Count大於等於多少次時中斷
try…catch…finally
try塊:拋出異常
catch塊:執行拋出異常後的操作
finally塊:不論是否拋出異常都會執行的操作
C#入門經典(第五版)學習筆記(二)