Invalid cast from 'System.Int32' to 'System.Nullable`1[[System.Int32, mscorlib]]

后端 未结 3 1259
误落风尘
误落风尘 2020-12-02 12:14
Type t = typeof(int?); //will get this dynamically
object val = 5; //will get this dynamically
object nVal = Convert.ChangeType(val, t);//getting exception here
         


        
3条回答
  •  遥遥无期
    2020-12-02 12:31

    You have to use Nullable.GetUnderlyingType to get underlying type of Nullable.

    This is the method I use to overcome limitation of ChangeType for Nullable

    public static T ChangeType(object value) 
    {
       var t = typeof(T);
    
       if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) 
       {
           if (value == null) 
           { 
               return default(T); 
           }
    
           t = Nullable.GetUnderlyingType(t);
       }
    
       return (T)Convert.ChangeType(value, t);
    }
    

    non generic method:

    public static object ChangeType(object value, Type conversion) 
    {
       var t = conversion;
    
       if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) 
       {
           if (value == null) 
           { 
               return null; 
           }
    
           t = Nullable.GetUnderlyingType(t);
       }
    
       return Convert.ChangeType(value, t);
    }
    

提交回复
热议问题