How to test whether a value is boxed in C# / .NET?

后端 未结 9 1279
终归单人心
终归单人心 2020-12-13 00:32

I\'m looking for a way to write code that tests whether a value is boxed.

My preliminary investigations indicate that .NET goes out of its way to conceal the fact,

9条回答
  •  时光说笑
    2020-12-13 01:07

    GetType() and IsValueType don't reveal the difference between a boxed value and an unboxed value.

    GetType is a sealed (non-virtual) method on System.Object. Calling this method on a value-type will definitely box it. Not even Nullable is able to get around this - calling GetType on a nullable will return the underlying type if it has a value (boxed as the underlying type) or throw a NullReferenceException if it doesn't (boxed to null, can't dereference a null-reference).

    when looking at any variable or value, even if its type is "dynamic" or "object," whether it's boxed or not boxed.

    In general, if you have an expression that "holds" a value-type, the value of that expression will be a reference to a box unless the expression's compile-time type is of the value-type itself (generics are slightly more complicated). Common reference-types that can hold references to boxed structures are object, dynamic and interface-types.

提交回复
热议问题