C# 当值可为null时,如何使用Convert.ChangeType(值,类型)

C# 当值可为null时,如何使用Convert.ChangeType(值,类型),c#,type-conversion,typeconverter,system.type,C#,Type Conversion,Typeconverter,System.type,当我试图将值转换为给定类型时,出现了一个异常,但该值包含null值 //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 pr

当我试图将值转换为给定类型时,出现了一个异常,但该值包含null值

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


如果有办法解决这个问题。

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

propertyVal = (propertyVal == null) ? null : Convert.ChangeType(propertyVal, targetType);
可能重复的