.net中的每种类型都继承自System.Object吗? [英] Does every type in .net inherit from System.Object?

查看:41
本文介绍了.net中的每种类型都继承自System.Object吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个非常基本的问题,但是我对此有些困惑.如果我反映了Int32/Double/任何值类型的代码,我会看到它们是结构,看起来像:

This might be a very basic question, but I am a bit confused about it. If I reflect the Int32/Double/any value type code, I see that they are structs and look like :

[Serializable, StructLayout(LayoutKind.Sequential), ComVisible(true)]
public struct Double : IComparable, IFormattable, IConvertible, IComparable<double>, IEquatable<double>
{
....
}

那么,为什么我们说.NET中的所有内容都源自System.Object.我认为这里缺少一些关键点.

So, why do we say that everything in .NET is derived from System.Object. I think am missing some crucial point here.

进一步令我困惑的是,结构的值类型如何从作为类的System.Object继承.

What confuses me further is that how can a value type which is struct inherit from System.Object which is a class.

推荐答案

Eric Lippert在博客条目中对此进行了介绍:

Eric Lippert has covered this in a blog entry: Not everything derives from object (This is the title of the blog entry; not the answer to this question. Don't get confused.)

是的,所有 struct 都继承自 System.ValueType ,而后者又继承自 System.Object .您声明的枚举是从 System.Enum 继承的,而 System.Enum 是从 System.ValueType 继承的.

Yes, all structs inherit from System.ValueType which in turn inherits from System.Object. enums you declare inherit from System.Enum which inherits from System.ValueType.

从本质上讲,从引用类型派生出值类型没有问题.继承是两个类型之间的是"关系.但是,为了将值类型视为对象实例,必须将其装箱.当您将值传递给需要对象参数的方法时(或调用在 System.Object 中实现的实例方法)时,将隐式完成此操作.

Inherently, there's not a problem with a value type being derived from a reference type. Inheritance is a "is-a" relationship between two types. However, in order to treat a value type as an object instance, it has to be boxed. This is done implicitly when you are passing a value to a method that expects an object parameter (or when you call instance methods implemented in System.Object.)

这篇关于.net中的每种类型都继承自System.Object吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆