C# Reflection: How to get the type of a Nullable?

后端 未结 5 1360
面向向阳花
面向向阳花 2021-01-01 11:04

What I want to do is something like this:

switch( myObject.GetType().GetProperty( \"id\") )
{
    case ??: 
        // when Nullable, do this
           


        
5条回答
  •  感动是毒
    2021-01-01 11:26

    In .net, instances of value types are just collections of bits, with no associated type information. For every value type other than Nullable, however, the system also auto-generates a corresponding class type which derives from System.ValueType. A widening conversion exists from the value type to the auto-generated class type, and a narrowing conversion from the auto-generated class type to the value type. In the case of Nullable, there is no corresponding auto-generated class type with conversions to/from the value type; instead, widening conversions exist in both directions between Nullable and the class type associated with T.

    As far as I can tell, this weird behavior was implemented to allow comparisons between null and an empty Nullable to return true.

提交回复
热议问题