反射赋值 解决类型转换异常的写法

                 //反射进行赋值时 防止类型转换异常的标准写法
                            Type type = Nullable.GetUnderlyingType(propertyInfo.PropertyType); //返回可为空字段的类型
                            if (type!=null)
                            {
                                propertyInfo.SetValue(model,string.IsNullOrEmpty(newValue)? null:Convert.ChangeType(newValue,type),null);
                            }
                            else
                            {
                                propertyInfo.SetValue(model,string.IsNullOrEmpty(newValue)? null:Convert.ChangeType(newValue,propertyInfo.PropertyType),null);
                            }

其中 newValue 是要设置的值

posted @ 2022-03-02 23:16  探索的动机  阅读(94)  评论(0编辑  收藏  举报