C#本当に分かったか?

3025 ワード

次のコードを見てください.結果が実際の状況と一致すれば、参照タイプがわかります.
    class Program

    {

        static void Main(string[] args)

        {

            Car theCar = new Car();

            TestClass(theCar);

            Console.WriteLine(theCar.Name);

            TestClass2(theCar);

            Console.WriteLine(theCar.Name);

            TestClass3(theCar);

            Console.WriteLine(theCar.Name);

            Console.ReadLine();



        }



        public static void TestClass(Car mycar)

        {

            mycar.Name = "aaa";

            mycar.Number = 100;

            mycar.ProductArea = "china";

        }



        public static void TestClass2(Car mycar)

        {

            Car thiscar = mycar;

            thiscar.Name = "bbb";

            thiscar.Number = 200;

            thiscar.ProductArea = "Japan";

        }



        public static void TestClass3(Car mycar)

        {

            Car thiscar = new Car(mycar);

            thiscar.Name = "ccc";

            thiscar.Number = 300;

            thiscar.ProductArea = "Korea";

        }

    }
    class Car

    {

        public string Name; 

        public string ProductArea;

        public int Number;



        public Car(Car thecar)

        {

            this.Name = thecar.Name;

            this.Number = thecar.Number;

            this.ProductArea = thecar.ProductArea;

        }

        public Car()

        {

            this.Name = null;

            this.Number = 0;

            this.ProductArea = null;

        }

    }

結果は次のとおりです.
aaa bbb bbb