Whats the use of Nullable.GetUnderlyingType, if typeof(int?) is an Int32?

前端 未结 5 2156
萌比男神i
萌比男神i 2021-02-05 16:07

why is typeof int? an Int32

int? x = 1;
Console.WriteLine(x.GetType().Name);

If it is okay then what\'s the use of

5条回答
  •  耶瑟儿~
    2021-02-05 16:45

    This example is a bit confused, because:

    int? x = 1;
    

    creates a Nullable like you expect; however:

    Type tupe = x.GetType();
    

    is a call to a non-virtual method on object, which isn't (and can't be) overridden - therefore this is a boxing operation; and Nullable has special boxing rules:

    • if it is empty, it boxes to null
    • if it has a value, the value is boxed and returned

    i.e.

    int? x = 1;
    int y = 1;
    

    box to exactly the same thing.

    Therefore, you are passing typeof(int) to GetUnderlyingType.

    A more illustrative example of when this helps is when using reflection:

    class Foo {
        public int? Bar {get;set;}
    }
    ...
    Type type = typeof(Foo); // usually indirectly
    foreach(var prop in type.GetProperties()) {
         Type propType = prop.PropertyType,
              nullType = Nullable.GetUnderlyingType(propType);
    
         if(nullType != null) {
             // special code for handling Nullable properties;
             // note nullType now holds the T
         } else {
             // code for handling other properties
         }
    }
    

提交回复
热议问题