Value Type Vs Reference Type - Object Class C#

前端 未结 1 1425
忘掉有多难
忘掉有多难 2020-12-06 18:59

if Value Types and Reference Type are from Object Type which is a reference type, then how value type is value type and reference type is reference when they all come from r

相关标签:
1条回答
  • 2020-12-06 19:31

    Basically, it is a cheat ;-p

    Any struct (i.e. anything inherited from ValueType) is treated with value-type semantics. But there is a boxing conversion to object as necessary; meaning that if you cast a struct to an object, it will create a special object (on the managed heap) containing the data (as a clone) from your value*.

    The boxed version is a reference-type. You can unbox this (by casting) back to the struct version, which reverses this (copies the clones data from the object on the heap into your local value).


    *=unless it is an empty Nullable<T>, which boxes to null; likewise, null unboxes to an empty Nullable<T>.

    0 讨论(0)
提交回复
热议问题