在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
首先明确一个概念:值传递和引用传递,是指在方法中传递参数的方式。 既然是在方法的区别的话,那么我们首先首先总结几个方法出来。
示例: 定义一个计算器类: 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; } } }
测试类: // 求和:值传递 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);
|
请发表评论