C#引用参数和值类型参数的区别

值参数的意义在于传进来的参数是该参数的副本,在传进来之后进行的改变,不会影响到该该参数本身的值

  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;
        }
    }  

 

posted @ 2020-06-14 22:02  仲夏不凉爽  阅读(412)  评论(0编辑  收藏  举报