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

前端 未结 5 2100
萌比男神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:20

    Mainly its for dealing with a generic method:: e.g.

    public static void SomeMethod(T argument)
    {
         if(Nullable.GetUnderlyingType(typeof(T) != null)
         {
                 /* special case for nullable code go here */
         }
         else
         {
                /* Do something else T isn't nullable */
         }
    }
    

    It's important to know this, as certain things that are very cheap can be wildly expensive on nullable's. For instance, if(argument == null) is normally super cheap, but when done in a generic method on a Nullable is forced to box the argument to get a null reference. Your best bet is to use EqualityComparer.Default which will slow everything else down, but makes nullable's not suffer.

提交回复
热议问题