首页 > 代码库 > ref引用类型,数组型参数,out输出参数

ref引用类型,数组型参数,out输出参数

ref和out的相同点和不同点

共同点:都是引用传递
不同点:ref的参数在调用之前一定要赋值,在方法调用的过程中可以不要赋值。
    out的参数在调用之前可以不赋值,在方法调用的过程中一定要赋值。

 

//方法的参数
    class Program
    {
        static void Main(string[] args)
        {
            //值传递
            //int num = 5;
            //Change(num);
            //Console.WriteLine("Main方法中的num为:"+num);

            //引用传递
            //int[] arr = { 1, 3, 5 };
            //Change(arr);
            //Console.WriteLine("Main方法中的arr[1]为:" + arr[1]);

            //ref参数(引用传递)
            //int num=5;
            //Change(ref num);//ref参数在调用前一定要赋值
            //Console.WriteLine("Main(ref)方法中的num为:" + num);

            //out参数(引用传递)
            //int num;
            //OutChange(out num);
            //Console.WriteLine("Main(out)方法中的num为:" + num);

            //数组型参数(引用传递)
            int result = Sum("*",3,5,6);
            Console.WriteLine(result);
        }

        public static void Change(int number)
        {
            number = 10;
            Console.WriteLine("Change中的number为:" + number);
        }

        public static void Change(int[] arr)
        {
            arr[1] = 100;
            Console.WriteLine("Change中的arr[1]为:" + arr[1]);
        }

        public static void Change(ref int number)
        {
            number = 10;
            Console.WriteLine("Change(ref参数)中的number为:" + number);
        }

        public static void OutChange(out int number)
        {
            number = 20;
            Console.WriteLine("OutChange(out参数)中的number为:" + number);
        }

        //注意:数组型参数一定要放在参数列表最后
        public static int Sum(string op,params int[] num)
        {
            if(op=="+")
            {
                int total = 0;
                for (int i = 0; i < num.Length; i++)
                {
                    total += num[i];
                }
                return total;
            }
            else if (op == "*")
            {
                int total = 1;
                for (int i = 0; i < num.Length; i++)
                {
                    total *= num[i];
                }
                return total;
            }
            else
            {
                Console.WriteLine("运算符只能是+/*");
                return -1;
            }
            
        }
    }