按值和按引用传递参数

using System;

namespace TEST
{
    class Program
    {
        static void Main(string[] args)
        {
            var structA = new StructA { X = 1 };
            ChangeStructA(structA);// struct为值类型 => 值传递
            Console.WriteLine(structA.X);// => 1

            ChangeStructA(ref structA);// struct引用传递 => 引用传递
            Console.WriteLine(structA.X);// => 2

            var classA = new ClassA { X = 1 };
            ChangeClassA(classA);// class为引用类型 => 引用传递
            Console.WriteLine(classA.X);// => 2

            var classB = new ClassB { X = 1 };
            ChangeClassB(classB);
            Console.WriteLine(classB.X);// => 2

            ChangeClassB(ref classB);
            Console.WriteLine(classB.X);// => 3
        }

        static void ChangeStructA(StructA a)
        {
            a.X = 2;
        }

        static void ChangeStructA(ref StructA a)
        {
            a.X = 2;
        }

        static void ChangeClassA(ClassA a)
        {
            a.X = 2;
        }

        static void ChangeClassB(ClassB b)
        {
            b.X = 2;
            b = new ClassB { X = 3 };//
        }

        static void ChangeClassB(ref ClassB b)
        {
            b.X = 2;
            b = new ClassB { X = 3 };//
        }
    }

    struct StructA
    {
        public int X { get; set; }
    }

    class ClassA
    {
        public int X { get; set; }
    }

    class ClassB
    {
        public int X { get; set; }
    }
}
posted @ 2018-08-01 22:13  老王子  阅读(253)  评论(0编辑  收藏  举报