日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#中的out參數、ref參數和params可變參數用法介紹_C#教程

作者:CosmosbipinnatusCav ? 更新時間: 2022-03-30 編程語言

out參數:

out關鍵字 通過引用來傳遞參數,在定義方法和調用方法的時候都必須使用out關鍵字

簡單來講out可以用來返回多個參數類型。

       static void Main(string[] args)
        {
            string s = "123";
            int result;
            bool b = MyTest(s,out result);
        }
        public static bool MyTest(string s, out int result)
        {
            bool isTrue;
            try {
                result = Convert.ToInt32(s);//使用out參數必須在定義方法內進行賦值
                isTrue = true;
            }
            catch
            {
                isTrue = false;
                result = 0;
            }
            return isTrue;
        }

該方法返回類型為bool類型,在返回bool類型的同時也順帶返回了int類型的result變量。即,返回兩種變量類型。

ref參數

ref參數在定義的方法內對其進行處理,再將結果返回,定義方法無需多余的返回類型。

ref參數和out 的的區別 out必須在定義方法內部賦值,ref必須在調用方法之前為其實參賦值。

        static void Main(string[] args)
        {
            //使用ref參數來交換兩個數字的值
            int a = 1;
            int b = 2;
            Change(ref a, ref b);
            Console.WriteLine("a{0},b{1}",a,b);
            Console.ReadKey();
        }
        public static void Change(ref int a, ref int b)
        {
            int temp;
            temp = a;
            a = b;
            b = temp;
        }

注意 在定義方法的時候 可以不需要返回值啦~

params可變參數

將實參列表中與可變參數數組類型一致的元素都當做數組的元素去處理。

params可變參數必須是形參的最后一個元素。

        static void Main(string[] args)
        {
            //方法一:可以使用數組傳參
            //int[] scores = {22,11,33};
            //test("張三",11,scores)
            //方法二:也可以直接在調用的時候使用和數組類型一致的元素
            test ("張三", 100, 22, 11, 33);
            Console.ReadKey();
        }
        /// <summary>
        /// params測試函數,計算一個同學的總成績
        /// 在params使用的時候必須將其放在最后一個參數,如下所示!
        /// </summary>
        /// <param name="name">姓名</param>
        /// <param name="number">學號</param>
        /// <param name="s">可變數組成績</param>
        public static void test(string name, int number, params int[] s)
        {
            int sum = 0;
            for (int i = 0; i < s.Length; i++)
            {
                sum = sum + s[i];
            }
            Console.WriteLine("{0}的學號是{1},總分為{2}", name, number, sum);
        }

原文鏈接:https://www.cnblogs.com/wy0904/p/8145202.html

欄目分類
最近更新