【发布时间】:2017-02-16 05:49:11
【问题描述】:
当我尝试将值转换为给定类型时出现异常,但值包含空值。
//find out the type
Type type = inputObject.GetType();
//get the property information based on the type
System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyName);
//find the property type
Type propertyType = propertyInfo.PropertyType;
//Convert.ChangeType does not handle conversion to nullable types
//if the property type is nullable, we need to get the underlying type of the property
var targetType = IsNullableType(propertyInfo.PropertyType) ? Nullable.GetUnderlyingType(propertyInfo.PropertyType) : propertyInfo.PropertyType;
//Returns an System.Object with the specified System.Type and whose value is
//equivalent to the specified object.
propertyVal = Convert.ChangeType(propertyVal, targetType);
这里,propertyVal = 持有空值,所以它会抛出异常。
InvalidCastException:Null 对象无法转换为值类型。
如果有办法解决这个问题。
【问题讨论】:
标签: c# type-conversion typeconverter system.type