如何在值可为空时使用Convert.ChangeType(value,type)

时间:2017-02-16 05:49:12

标签: c# type-conversion typeconverter system.type

当我尝试将值转换为给定类型时,我遇到了异常,但值保持为空值。

//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对象转换为值类型。

如果有任何方法可以解决此问题。

1 个答案:

答案 0 :(得分:1)

你能做的最简单的事就是

propertyVal = (propertyVal == null) ? null : Convert.ChangeType(propertyVal, targetType);
相关问题