值类型从System.Object继承......为什么? [英] Value types inherit from System.Object...why?
问题描述
可能显示的文件:结果
的是一个对象的一切.NET?结果
的如何从值类型派生的对象(引用类型),仍然是值类型?
我只是不明白这一点。 System.Object的是(我认为)引用类型,但它在.NET中继承所有的数据类型。还值类型做的一样好。我不明白 - 值类型的值都在栈中,但其从Object继承?
希望有人可以帮助我了解
Hi, I just do not get it. System.Object is (I think) reference type but all data types in .NET inherit from it. Also value types do as well. I do not understand it - value type has its value on the stack but its inherited from Object? Hope anyone could help me to understand
推荐答案
问自己,为什么你认为这是奇怪的是,这通常是分配的类型在堆栈上将从 System.Object的
继承,我想你会发现你不能制定一个很好的理由。
Ask yourself why you think it's strange that a type that is typically allocated on the stack would inherit from System.Object
and I think you'll find you can't formulate a good reason.
如果您认为这是因为一个对象的键入的定义在那里被分配,你错了。哪些成员值类型
是负责定义它的分配机制? (什么成员 System.Object的
的,对于这个问题?)
If you think it's because an object's type defines where it is allocated, you're mistaken. What member of ValueType
is responsible for defining its allocation mechanism? (What member of System.Object
, for that matter?)
在.NET类型继承应该包括是的关系:一个字符串
是 对象
,例如。的一切的在.NET世界的是的对象
,所以一个 INT
是对象
,一个双击
是对象
等。
Type inheritance in .NET is supposed to comprise "is a" relationships: a string
is an object
, for example. Everything in the .NET world is an object
, so an int
is an object
, a double
is an object
, etc.
您可以在里氏替换原则:如果我写了期望一个对象
代码,我应该能够处理的任何的类型的是的对象
- 即,任何东西。我的代码应该是一个字符串
,一个 INT
同样舒适,一个列表< INT>
等
You can think of this in terms of the Liskov substitution principle: if I write code that expects an object
, I should be capable of dealing with any type that is an object
—i.e., anything at all. My code should be equally comfortable with a string
, an int
, a List<int>
, etc.
另外请注意,对象
保证某些成员所有类型有作为这样做的结果:的GetType
,的ToString
和的GetHashCode
Also note that object
guarantees certain members that all types have as a consequence of this: GetType
, ToString
, and GetHashCode
.
这篇关于值类型从System.Object继承......为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!