2
値が与えられた型に変換しようとしているときに例外が発生しましたが、値にnull値が入ります。値がnullableのときに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 =はnull値を保持するため、例外をスローします。
InvalidCastException:Nullオブジェクトを値型に変換できません。
この問題を解決する方法があれば。
可能性のある重複した[Convert.ChangeTypeは()のNullable型に失敗した]される(http://stackoverflow.com/questions/3531318/convert-changetype-fails -nullable-types) –