将 Nothing 转换为 Nullable(Of )
Convert Nothing into Nullable(Of )
我想将空值转换为 Nullable(Of ) 类型。我可以用 CType() 转换它,但不能用 System.Convert.ChangeType().
转换它
有办法吗?为什么会抛出异常?
Dim b as Boolean? = CType(Nothing, Boolean?) 'ok
System.Convert.ChangeType(Nothing, GetType(Boolean?)) 'Throws System.InvalidCastException
Is there a way to do so?
Dim valueNothing = ConvertHelper.SafeChangeType(Of Boolean)(Nothing)
Dim valueTrue = ConvertHelper.SafeChangeType(Of Boolean)(True)
Dim valueFalse = ConvertHelper.SafeChangeType(Of Boolean)(False)
' ...
Class ConvertHelper
Shared Function SafeChangeType(Of T As Structure)(ByVal value As Object) As T?
Return If(value Is Nothing, Nothing, DirectCast(Convert.ChangeType(value, GetType(T)), T?))
End Function
End Class
Why it throws an exception?
由于Convert.ChangeType
方法implementation:
if( value == null ) {
if(conversionType.IsValueType) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCastNullToValueType"));
}
return null;
}
我想将空值转换为 Nullable(Of ) 类型。我可以用 CType() 转换它,但不能用 System.Convert.ChangeType().
转换它有办法吗?为什么会抛出异常?
Dim b as Boolean? = CType(Nothing, Boolean?) 'ok
System.Convert.ChangeType(Nothing, GetType(Boolean?)) 'Throws System.InvalidCastException
Is there a way to do so?
Dim valueNothing = ConvertHelper.SafeChangeType(Of Boolean)(Nothing)
Dim valueTrue = ConvertHelper.SafeChangeType(Of Boolean)(True)
Dim valueFalse = ConvertHelper.SafeChangeType(Of Boolean)(False)
' ...
Class ConvertHelper
Shared Function SafeChangeType(Of T As Structure)(ByVal value As Object) As T?
Return If(value Is Nothing, Nothing, DirectCast(Convert.ChangeType(value, GetType(T)), T?))
End Function
End Class
Why it throws an exception?
由于Convert.ChangeType
方法implementation:
if( value == null ) {
if(conversionType.IsValueType) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCastNullToValueType"));
}
return null;
}