ITPub博客

首页 > 应用开发 > IT综合 > C#入门经典(第五版)学习笔记(二)

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

原创 IT综合 作者:shan__bin 时间:2014-06-19 22:56:50 0 删除 编辑

---------------函数---------------
参数数组:可指定一个特定的参数,必须是最后一个参数,可使用个数不定的参数调用函数,用params关键字定义它们
例如:
static int SumVals(params int[] vals)
{
    int sum = 0;
    foreach(int val in vals)
    {
        sum += val;
    }
    return sum;
}
调用SumVals:    int sum = SumVals(1,2,5,7,8,12,34);
结果sum=69

引用参数:关键字ref,传递参数本身而非传递参数的值
例如:
static void ShowDouble(ref int val)
{
    val *= 2;
}
int i = 5;
ShowDouble(ref i);
结果i=10

输出参数:关键字out,传出参数
例如:
static int MaxValue(int[] intArray,out int maxIndex)
{
    int maxVal = intArray[0];
    maxIndex = 0;
    for (int i = 0; i < intArray.Length; i++)
    {
        if (intArray[i] > maxVal)
        {
            maxIndex = i;
            maxVal = intArray[i];
        }
    }
    return maxVal;
}
调用MaxValue:
int[] intArray = {1,2,5,7,8,12,34};
int maxIndex,maxValue;
maxValue = MaxValue(intArray,out maxIndex)
结果maxIndex = 6

委托实例:
    class Program
    {
        delegate double ProcessDelegate(double param1, double param2);

        static double Multiply(double param1, double param2)
        {
            return param1 * param2;
        }
        static double Divide(double param1, double param2)
        {
            return param1 / param2;
        }

        static void Main(string[] args)
        {
            ProcessDelegate process;
            Console.WriteLine("2 number");
            string input = Console.ReadLine();
            int commaPos = input.IndexOf(',');
            double param1 = Convert.ToDouble(input.Substring(0, commaPos));
            double param2 = Convert.ToDouble(input.Substring(commaPos + 1, input.Length - commaPos - 1));
            Console.WriteLine("xxx");
            input = Console.ReadLine();
            if (input == "M")
                process = new ProcessDelegate(Multiply);
            else
                process = new ProcessDelegate(Divide);
            Console.WriteLine("Result: {0}", process(param1, param2));
            Console.ReadKey();
        }
    }

---------------调试和错误处理---------------
断点可选择性触发,列表如下:
1)总是中断
2)在Hit Count等于多少次时中断
3)在Hit Count是某个数的倍数时中断
4)在Hit Count大于等于多少次时中断

try…catch…finally
try块:抛出异常
catch块:执行抛出异常后的操作
finally块:不论是否抛出异常都会执行的操作

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/10663598/viewspace-1189490/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2014-05-23

  • 博文量
    7
  • 访问量
    11916