C#引用参数和值类型参数的区别
时间:2020-06-14 22:44:25
收藏:0
阅读:57
值参数的意义在于传进来的参数是该参数的副本,在传进来之后进行的改变,不会影响到该该参数本身的值
class Program { static void Main(string[] args) { Student stu = new Student(); Acess ac = new Acess(); ac.Max(stu.Age); Console.WriteLine("{0},{1}",stu.GetHashCode(),stu.Age); } class Acess { public void Max(int a) { a =a+18; Console.WriteLine("{0},{1}",a.GetHashCode(),a); } } class Student { public int Age=10; } }
而引用类型的参数要加修饰符ref,而且传参数之前要明确的给这个参数赋值,传进来的参数是这个参数的地址值,不会创建该参数的副本,所以传进来的参数值发生了改变,那么本体也会被改变
class Program { static void Main(string[] args) { Student stu = new Student(); Acess ac = new Acess(); ac.Max(ref stu.Age); Console.WriteLine("{0},{1}",stu.GetHashCode(),stu.Age); } class Acess { public void Max(ref int a) { a =a+18; Console.WriteLine("{0},{1}",a.GetHashCode(),a); } } class Student { public int Age=10; } }
原文:https://www.cnblogs.com/zxbls/p/13127304.html
评论(0)