微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 对象是引用类型还是值类型?

我仍然怀疑对象.它是任何类,任何类的主要基类.但是它是引用类型还是值类型.还是喜欢这些行为呢?我需要澄清这一点.我很难理解.
object obj1 = "OldString";
     object obj2 = obj1;
     obj1 = "NewString";
     MessageBox.Show(obj1 + "   " + obj2);
     //Output is  "NewString   OldString"

在这种情况下,它的行为就像一个值类型.如果对象是引用类型,那么为什么obj2值仍然是“OldString”

class SampleClass
    {
        public string Text { get; set; }
    }

    SampleClass Sample1 = new SampleClass();
    Sample1.Text="OldText";         

    object refer1 = Sample1;
    object refer2 = refer1;

    Sample1.Text = "NewText";

    MessageBox.Show((refer1 as SampleClass).Text +  (refer2 as SampleClass).Text);
    //OutPut is "NewText   NewText"

在这种情况下,它的作用就像参考类型

我们可以推断,对象的类型是你内部的框.它可以是引用类型和值类型.这是关于你的盒子里面.我对吗?

解决方法

它是一个参考类型

使用字符串做一个例子不是很明亮,因为字符串也是一个引用类型(显然是SampleClass);你的例子包含零“拳击”.

if object is reference type then why obj2 value is still “OldString”

为什么不这样?当您创建一个新的字符串时,不会更改旧的引用来指向新的字符串.考虑:

object obj1 = "OldString";
 // create a new string; assign obj1 the reference to that new string "OldString"

object obj2 = obj1;
 // copy the reference from obj1 and assign into obj2; obj2 Now refers to
 // the same string instance

 obj1 = "NewString";
 // create a new string and assign that new reference to obj1; note we haven't
 // changed obj2 - that still points to the original string,"OldString"

原文地址:https://www.jb51.cc/csharp/95009.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐