首页 > 其他 > 详细

对象间引用赋值及方法时引用传递

时间:2016-11-16 11:16:57      阅读:205      评论:0      收藏:0      [点我收藏+]

考虑下面代码:

    class Program
    {
        static void Main(string[] args)
        {
            C c1 = new C();
            c1.str = "hello";

            C c2 = new C();
            c2 = c1; //对象名即是对象引用,对象间赋值即是引用复制赋值,此时栈区的c2和c1同时指向堆区的同一块内存区域

            Console.WriteLine(c1.str);
            Console.WriteLine(c2.str);

            c2.str = "world";
            Console.WriteLine(c1.str);
            Console.WriteLine(c2.str);

            Set(c1,"test1");
            Console.WriteLine(c1.str);
            Console.WriteLine(c2.str);

            Set(c2, "test2");
            Console.WriteLine(c1.str);
            Console.WriteLine(c2.str);

            Console.ReadKey();
        }

        //对象名作为参数传入时,传入的是对象的引用
        public static void Set(C c,string msg)
        {
            c.str = msg;
        }
    }

    class C
    {
        public string str = string.Empty;
    }

体会输出结果:

技术分享

 

对象间引用赋值及方法时引用传递

原文:http://www.cnblogs.com/Arlar/p/6068633.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!