C# 引用类型和值类型

概念:

参考链接:http://www.cnblogs.com/xiaobudong/p/6687259.html

参考链接:http://www.cnblogs.com/renyiqiu/p/6435261.html

 

个人总结:

static void Main(string[] args)
        {
            int a = 1;
            int b = a;
            a = 2;

            Console.WriteLine("a的值:a="+ a + ";b的值为:b="+b);


            string stra = "hello";
            string strb = stra;
            stra = "world";
            if (stra.Equals(strb))
            Console.WriteLine("a的值:stra=" + stra + ";strb的值为:strb=" + strb);

            Console.WriteLine("Reference equal for string: " + Object.ReferenceEquals(a, b));
            //false
            Console.WriteLine("Reference equal for string: " + Object.ReferenceEquals(stra, strb));
            //true
            Console.ReadKey();
        }

结果:

注:Object.ReferenceEquals:确定指定的 System.Object 实例是否是相同的实例,返回结果:如果 objA 是与 objB 相同的实例,或者如果二者都为空引用,则为 true;否则为 false。

总结:

  当变量为值类型时,系统在栈上为a和b分配了不同的存储空间;当变量为引用类型时,系统为stra和strb分配了相同的存储空间。

 

 

posted @ 2017-04-11 14:54  *ち黑サカ  阅读(163)  评论(0编辑  收藏  举报