开发者

How are value types like objects?

I have read the following statement from the Microsoft .NET Framework App Development toolkit:

"Even though value types often represent simple values, they still function as Objects"

Can anyone help开发者_高级运维 me understand how value types function as objects?

saj


If they only were values you couldn't call member functions on them (there's some magic behind the scenes though: (un)boxing).

2.toString() works (2 being a value type), while you would be unable to implement this in other languages where you have real values like C.

Note: An article on value types in C#. Excerpt: Even though value types often represent simple values, they still function as objects. In other words, you can call methods on them. In fact, it is common to use the ToString method when displaying values as text. ToString is overridden from the fundamental System.Object type.


Read this (boxing and unboxing).


For every value type other than Nullable<T> the system defines a corresponding class type derived from ValueType, which in turn derives from Object. If it is necessary to place something of value type into a class-type storage location, the system will implicitly convert the value type into the class type. Note that although the compiler will claim that the resulting object instance is a value type, the instance will in fact have class-type semantics. This is primarily of importance to value types which implement interfaces (e.g. List<T>.Enumerator is a struct which implements IEnumerator<T>). Although interfaces used in constraints are neither value types nor class types, storage locations (variables, fields, etc.) of interface types are always stored as class types and object instances stored in them behave as class-types instances.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜