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); 
相關問題