首先明確一個概念:值傳遞和引用傳遞,是指在方法中傳遞參數的方式。數組
既然是在方法的區別的話,那麼咱們首先首先總結幾個方法出來。測試
傳遞類型 | 參數數據類型爲值類型和引用數據類型 | 特色 |
值傳遞 | Sum(int num1,int num2) | 修改了形參內容,結果不會保留 |
Sum(int [] num1) | 修改了形參內容,結果會保留 | |
引用傳遞 | Sum(ref int num1,ref int num2) | 使用 ref ,實參必需要初始化賦值;修改了形參內容,結果會保留 |
Sum(out int num1,out int num2) | 使用out,形參必需要賦值;修改了形參內容,結果會保留 |
示例:spa
定義一個計算器類:code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson3 { /// <summary> /// 計算器類 /// </summary> public class Calc { /// <summary> /// 求和:參數是int——值類型 /// </summary> public int Sum(int num1, int num2) { int sum = 0; num1 = 10; sum = num1 + num2; return sum; } /// <summary> /// 求和:參數是數組——引用類型 /// </summary> public int SumParam(int[] nums) { nums[0] = 10; int sum = nums[0] + nums[1]; return sum; } /// <summary> /// 求和:參數是值類型——引用傳遞 /// </summary> public int SumRef(ref int num1, ref int num2) { int sum = 0; num1 = 10; sum = num1 + num2; return sum; } /// <summary> /// 交換兩個數 /// </summary> /// <param name="num1"></param> /// <param name="num2"></param> public void Swap(int num1,int num2) { int temp = 0; temp = num1; num1 = num2; num2 = temp; } /// <summary> /// 交換兩個數 /// </summary> /// <param name="num1"></param> /// <param name="num2"></param> public void SwapRef(ref int num1, ref int num2) { int temp = 0; temp = num1; num1 = num2; num2 = temp; } } }
測試類:blog
// 求和:值傳遞 Calc calc = new Calc(); int num1 = int.Parse(Console.ReadLine()); int num2 = int.Parse(Console.ReadLine()); // int sum = calc.Sum(num1, num2); // 輸出和 Console.WriteLine(num1 + "+" + num2 + "=" + sum); // 求和:參數是數組——值傳遞 Calc calc1 = new Calc(); int[] nums = { 1, 2 }; int sum1 = calc1.SumParam(nums); // 輸出和 Console.WriteLine(nums[0] + "+" + nums[1] + "=" + sum1); // 求和:參數是ref關鍵字——引用傳遞 Calc calc2 = new Calc(); int refNum1 = 1; int refNum2 = 2; int refSum = calc2.SumRef(ref refNum1, ref refNum2); // 輸出和 Console.WriteLine(refNum1 + "+" + refNum2 + "=" + refSum); // 交換兩個數 //Calc calc = new Calc(); //int num1 = 8; //int num2 = 10; //Console.WriteLine("值傳遞:交換前的數是" + num1 + "," + num2); //// 交換 //calc.Swap(num1, num2); //Console.WriteLine("值傳遞:交換後的數是" + num1 + "," + num2); //int num1Ref = 8; //int num2Ref = 10; //Console.WriteLine("引用傳遞:交換前的數是" + num1Ref + "," + num2Ref); //// 交換 //calc.SwapRef(ref num1Ref, ref num2Ref); //Console.WriteLine("引用傳遞:交換後的數是" + num1Ref + "," + num2Ref);