从可空类型到基础类型的转换

时间:2021-12-17 15:45:34

在做一些复杂的类型转换之前(比如将一个数据转换成一个属性的类型,属性可能为可空类型)先判断该类型是否为可空类型,否则会报如下错误:

从“System.String”到“System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]”的强制转换无效。

 Type type = typeof(Model.Users).GetProperties()[i].PropertyType;


                                //判断type类型是否为泛型,因为nullable是泛型类,
                                if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))//判断convertsionType是否为nullable泛型类
                                     
                                {
                                    //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
                                    System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(type);
                                    //将type转换为nullable对的基础基元类型
                                    type = nullableConverter.UnderlyingType;
                                }

                                typeof(Model.Users).GetProperty(typeof(Model.Users).GetProperties()[i].Name).SetValue(u,Convert.ChangeType(dic[item],type), null);

                               Type type = typeof(Model.Users).GetProperties()[i].PropertyType;


                                //判断type类型是否为泛型,因为nullable是泛型类,
                                if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))//判断convertsionType是否为nullable泛型类
                                    
                                {
                                    //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
                                    System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(type);
                                    //将type转换为nullable对的基础基元类型
                                    type = nullableConverter.UnderlyingType;
                                }

                                typeof(Model.Users).GetProperty(typeof(Model.Users).GetProperties()[i].Name).SetValue(u,Convert.ChangeType(dic[item],type), null);