Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

.net - Do value types (Integer, Decimal, Boolean, etc...) inherit from Object?

Looking for clarification on this...

I've heard that 'everything' in .Net inherits from Object. I've also heard that the difference between value types and reference types is that reference types inherit from Object and value types do not.

My understanding was that everything was an object (inherits from System.Object); but value types and reference types were simply 'different' from one another. Value types are allocated on the stack and reference types get a 'pointer' placed on the Stack that points to an address on the Heap.

Is that the gist of it? What makes an Integer a value type? That's something inherent in the language?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It depends on how you view the terminology - which depends on whether you're talking about C# or the CLI spec. For example, in the CLI spec (ECMA-355) sections 8.9.8 and 8.9.10 state:

Value types do not inherit, although the associated boxed type is an object type and hence inherits from other types.

and

In their unboxed form value types do not inherit from any type. Boxed value types shall inherit directly from System.ValueType unless they are enumerations, in which case, they shall inherit from System.Enum. Boxed value types shall be sealed.

So from the CLI's point of view, the answer to the question is no.

However, let's look at the C# spec - and as we're in an ECMA-like mood, let's go for that version (which is currently stuck at C# 2). Section 11.1.1 states:

All value types implicitly inherit from the class System.ValueType, which, in turn, inherits from class object.

So from the C# specification's point of view, the answer is yes.

One could argue that you tagged your question ".net" so we should use the CLI definition; if you'd tagged it "c#" we should have used the C# definition. See how arbitrary it is? :)

All of this spec-diving isn't to much practical purpose though. The answer depends on the intricacies of definitions. It's more sensible to construct some interesting situation where it matters... so what do you want to do? If you can present some code, we can answer questions about what will happen - and that's more important than definitions.

(Yes, this is unusual for me - in general, terminology matters a lot to me. In some cases, however, the subtleties are more of a curse than a blessing.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...