C#高級參數ref的使用


ref關鍵字用於將方法內的變量改變后帶出方法外。具體我們通過例子來說明:

例子中,將變量n1和n2交換了。如果沒有加ref參數,由於沒有swadDemo()方法沒有返回值,調用后,n1和n2是不會交換的,但是加了ref后,變量便會在swadDemo()中改變后並帶出。

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace blog { class Program { static void Main(string[] args) { refDemo(); } #region 使用高級參數ref
        private static void refDemo() { int n1 = 1; int n2 = 2; swadDemo(ref n1, ref n2); Console.WriteLine("n1:" + n1 + "\r\n" + "n2:" + n2); Console.ReadLine(); } #endregion

        #region 高級參數ref用法
        public static void swadDemo(ref int a, ref int b) { //注意,這個方法中,並沒有返回值。但是,由於加了ref, //所以會將變量改變后再帶出。 //ref參數,用於將方法內的變量改變后帶出方法外
            int temp; temp = a; a = b; b = temp; } #endregion } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM