2017-02-16 72 views
2

我得到一个异常,当我试图将值转换为给定类型,但值保留为空值。如何在值为空时使用Convert.ChangeType(value,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:空对象不能转换为值类型。

如果有什么方法可以解决这个问题。

+1

的可能的复制[Convert.ChangeType()上可空类型失败(http://stackoverflow.com/questions/3531318/convert-changetype-fails -on可空类型) –

回答

1

你可以做的事情simpliest只是

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