加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:41:17 所属栏目:百科 来源:网络整理
导读:我仍然怀疑对象.它是任何类,任何类的主要基类.但是它是引用类型还是值类型.还是喜欢这些行为呢?我需要澄清这一点.我很难理解. object obj1 = "OldString"; object obj2 = obj1; obj1 = "NewString"; MessageBox.Show(obj1 + " " + obj2); //Output is "NewS
我仍然怀疑对象.它是任何类,任何类的主要基类.但是它是引用类型还是值类型.还是喜欢这些行为呢?我需要澄清这一点.我很难理解.
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"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读