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

后端 未结 5 1319
面向向阳花
面向向阳花 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:09

    I've been using the following type of code to check if the type is nullable and to get the actual type:

    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
    {
        return Nullable.GetUnderlyingType(type);
    }
    

    If the type is e.g. Nullable this code returns the int part (underlying type). If you just need to convert object into specific type you could use System.Convert.ChangeType method.

提交回复
热议问题