我对object仍然有疑问。它是任何类别的基本基类。但是它是引用类型还是值类型。还是喜欢这些行为中的哪个?我需要弄清楚这一点。我很难理解。

     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"

在这种情况下,它的作用类似于引用类型

我们可以推断出object的类型就是您在其中装箱的类型。它可以是引用类型,也可以是值类型。这是关于您装箱的物品。我对吗?

最佳答案

是引用类型

用string做示例不是很有启发性的,因为string是还是引用类型(显然是SampleClass);您的示例包含零“装箱”。



为什么不呢?创建新字符串时,不会更改旧引用以指向新字符串。考虑:

 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"

09-10 04:38
查看更多