.net里的ref、out、params参数。

时间:2021-01-16 03:37:44

1、ref參數

    class Program
    {
        static void Main(string[] args)
        {
            int a = 10;
            int b = 5;
            ChangeNumValue(ref a, ref b);
            Console.WriteLine(a + " " + b);
            Console.ReadKey();
        }

        /// <summary>
        /// ref參數 側重於將一個值帶到函數中進行改變,再將改變后的值帶出去。ref在函數内不用賦值,函數外必須為ref參數賦值。
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        public static void ChangeNumValue( ref int a,ref int b) {
            int temp = a;
            a = b;
            b = temp;
        }
    }

2、out參數

  class Program
    {
        static void Main(string[] args)
        {
            int number;
            string str;
            bool b = Test(out number, out str);
            Console.WriteLine(number + "  " + str);
            Console.ReadKey();
        }
        /// <summary>
        /// out 参数侧重于在函数中返回多个值,out参数必须要求在函数内部中为其赋值。
        /// </summary>
        /// <param name="number"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool Test(out int number, out string str) {
            str = "hello";
            number = 10;
            return true;
        }
    }

3、params參數 

    //params 參數必須作爲形參中的最後一位參數。

        public static void TestParams(int number, params string[] strArray) {


        }

 

  調用:

            string[] strArr = { "Hello", "world" };
            TestParams(8, strArr);
            TestParams(8,"Hello","World");