C#入门经典(第五版)学习笔记(二)

---------------函数---------------
参数数组:可指定一个特定的参数,必须是最后一个参数,可使用个数不定的参数调用函数,用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              else
27                  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块:不论是否抛出异常都会执行的操作

posted @ 2015-05-05 10:07  苍苔幽井独自空  阅读(153)  评论(0编辑  收藏  举报