1. 程式人生 > >2018-10-14 ref引用傳遞 out引數

2018-10-14 ref引用傳遞 out引數

ref引數

將一個變數傳入一個函式中進行 “處理”,“ 處理”完成後,再將“處理”結果帶出函式

要求:

函式外必須為變數賦值,而函式內可以不賦值。

語法

形參和實參前都要加ref關鍵字。

 

 

    static void Main(string[] args)
        {
            int num = 5;

            Add(ref num);


            Console.WriteLine(num);
            Console.ReadKey();


        }
        static void Add(ref int num)
        {
            num += 10;
            Console.WriteLine(num);
        }

  static void Main(string[] args)
        {
            int num = 5;

            Add(ref num);


            Console.WriteLine(num);
            Console.ReadKey();


        }
        static void Add(ref int num)
        {
            num += 10;
            Console.WriteLine(num);
        }

 

out引數

一個函式中如果返回多個不同型別的值,就需要用到out引數。

函式外可以不為變數賦值,函式內,必須為其賦值。

 

static void Main(string[] args)
        {
            //out引數
            //申明一個Number 函式 傳遞兩個值過去,返回最大,最小,和,平均數
            int a = 10;
            int b = 5;

            int _max;
            int _min;
            int _total;
            double _avg;

            Number(a, b,out _max,out _min,out _total,out _avg);

            Console.WriteLine($"max:{_max},min:{_min},total:{_total},avg:{_avg}");

            Console.ReadKey();

        }

        static void Number(int a, int b,out int max,out int min,out int total,out double avg)
        {
            if (a > b)
            {
                max = a;
                min = b;
            }
            else
            {
                max = b;
                min = a;
            }
            total = a + b;
            avg = total / 2;

        }

 static void Main(string[] args)
        {
            //out引數
            //申明一個Number 函式 傳遞兩個值過去,返回最大,最小,和,平均數
            int a = 10;
            int b = 5;

            int _max;
            int _min;
            int _total;
            double _avg;

            Number(a, b,out _max,out _min,out _total,out _avg);

            Console.WriteLine($"max:{_max},min:{_min},total:{_total},avg:{_avg}");

            Console.ReadKey();

        }

        static void Number(int a, int b,out int max,out int min,out int total,out double avg)
        {
            if (a > b)
            {
                max = a;
                min = b;
            }
            else
            {
                max = b;
                min = a;
            }
            total = a + b;
            avg = total / 2;

        }