新手C#参数类型ref、out、params的学习2018.08.04

 

ref用于传递参数时,将实参传递到函数中,是引用参数,在使用前必须被赋值。string类型也同样适用。

        static void Main(string[] args)
        {
            string a1,a2;
            int i = 10, j = 20;
            swap(ref i, ref j);
            Console.WriteLine("i={0},j={1}",i, j);
            Console.ReadKey();
        }
        static void swap(ref int i,ref int j)//ref用于调用原本变量,而非函数中不影响变量的情况
        {
            int temp;
            temp=i;
            i = j;
            j = temp;
        }

out为输出参数,可以用于使函数返回不止一类返回值,且out参数不需要赋初值,out可以用于判断函数执行是否符合要求。

        //用于将汉字的数字转换为阿拉伯数字
        static void Main(string[] args)
        {
            int num;
            bool b;
            string s;
            s = Console.ReadLine();
            num=Parse(s,out b);
            if (b == true)//通过b的值判断输入的是否为有效汉字
            {
                Console.WriteLine("success 
{0}",num);
            }
            else
            {
                Console.WriteLine("false");
            }
            Console.ReadKey();
        }
        static int Parse(string s,out bool success)
        {
            if(s=="一")//设定两个有效汉字
            {
                success = true;
                return 1;
            }
            else if(s=="二")
            {
                success = true;
                return 2;
            }
            else
            {
                success = false;
                return -1;
            }
        }

 

可变参数即采用数组形式传递参数,在数据类型前加params表示可变参数,例如static int Max(params int[] values),作用在于调用Max函数时不需要先定义一个数组,可以直接输入数据,Console.WriteLine("{0}", Max(3, 5, 4, 7, 8, 9))。注:可变参数数组必须是最后一个。

 

        static void Main(string[] args)
        {
            Console.WriteLine("{0}", Max(3, 5, 4, 7, 8, 9));
            SayHello("big");
            Console.ReadKey();
        }
        static int Max(params int[] values)//可变参数params,以数组形式传递
        {
            int max = 0;
            foreach(int value in values)
            {
                if (value > max)
                    max = value;
            }
            return max;
        }

 

参数默认值即在定义函数时参数给定一个默认值,当使用时未给参数指定值时采用默认值。

 

        static void Main(string[] args)
        {
            SayHello("big");
            Console.ReadKey();
        }

        static void SayHello(string name,int age=20)
        {
            Console.WriteLine("我是{0},我今年{1}", name, age);
        }

 

其输出结果则是我是big,我今年20,若指定age则会输出指定的age的大小,用重载实现参数默认值的效果在构造函数中用的较多。

 

2018.08.04

原文地址:https://www.cnblogs.com/do-hardworking/p/9418564.html