【问题标题】:How to use the Convert.ChangeType(value, type) when the value is nullable当值可以为空时如何使用 Convert.ChangeType(value, type)
【发布时间】: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


【解决方案1】:

你能做的最简单的事情就是

propertyVal = (propertyVal == null) ? null : Convert.ChangeType(propertyVal, targetType);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-19
    • 2020-04-26
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 2014-01-05
    • 2011-04-01
    相关资源
    最近更新 更多