2017-02-16 19 views
2

У меня есть исключение, когда я пытаюсь преобразовать значение в заданный тип, но значение имеет значение null.Как использовать Convert.ChangeType (значение, тип), когда значение равно nullable

//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); 

Здесь свойствоVal = содержит пустое значение, поэтому оно выдает исключение.

InvalidCastException: Объект Null нельзя преобразовать в тип значения.

Если есть возможность исправить эту проблему.

+1

Возможный дубликат [Convert.ChangeType() терпит неудачу на обнуляемых типов] (http://stackoverflow.com/questions/3531318/convert-changetype-fails -он-обнуляемый-тип) –

ответ

1

Самый простой, что вы можете сделать, это просто

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