对象是引用类型还是值类型? [英] Is object a reference type or value type?
问题描述
我仍然对object
存有疑问.它是任何类,任何类的主要基础类.但是它是引用类型还是值类型.还是喜欢这些行为中的哪一个?我需要弄清楚这一点.我很难理解.
I have still doubts about object
. It is the primary base class of anything, any class. But is it reference type or value type. Or like which of these acts it? I need to get this clarified. I have difficulty understanding that.
object obj1 = "OldString";
object obj2 = obj1;
obj1 = "NewString";
MessageBox.Show(obj1 + " " + obj2);
//Output is "NewString OldString"
在这种情况下,它的作用类似于值类型.如果对象是引用类型,那么为什么obj2值仍然是"OldString"
In this case it acts like a value type. If object was reference type then why obj2 value is still "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"
在这种情况下,它的作用类似于引用类型
In this case it acts like reference type
我们可以推断出object
的类型就是您在其中键入的内容.它可以是引用类型,也可以是值类型.这是关于您在其中装箱的物品.我说的对吗?
We can deduce that object
's type is what you box inside it. It can be both a reference type and value type. It is about what you box inside. Am I right?
推荐答案
它是引用类型
使用string进行示例不是很有启发性,因为string也是也是引用类型(显然,SampleClass
也是);您的示例包含零装箱".
Doing an example with string isn't very illuminating, because string is also a reference type (as is SampleClass
, obviously); your example contains zero "boxing".
如果对象是引用类型,那么为什么obj2值仍为"OldString"
if object is reference type then why obj2 value is still "OldString"
为什么不呢?创建新字符串时,不会更改旧引用以指向新字符串.考虑:
Why wouldn't it be? When you create a new string, that doesn't change old references to point at the new string. Consider:
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"
这篇关于对象是引用类型还是值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!