2015-05-29 83 views
0

我想将null值转换为Nullable(Of)类型。我可以使用CType()进行强制转换,但不能使用System.Convert.ChangeType()进行转换。将Nothing转换为Nullable(Of)

有没有办法做到这一点?为什么它会抛出异常?

Dim b as Boolean? = CType(Nothing, Boolean?) 'ok 
System.Convert.ChangeType(Nothing, GetType(Boolean?)) 'Throws System.InvalidCastException 
+2

http://stackoverflow.com/questions/3531318/convert-changetype-fails-on-nullable-types – Eric

+2

有什么用'没有在_simply_问题'直接在'Dim b As Boolean? =没有'? – Sehnsucht

+0

@Sehnsucht它是一个代码片段。在我的项目中,它可以是每种类型,不仅是'布尔?'。 – user2190035

回答

2

有没有办法这样做呢?

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 

为什么它抛出一个异常?

由于Convert.ChangeType方法implementation

if(value == null) { 
    if(conversionType.IsValueType) { 
     throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCastNullToValueType")); 
    } 
    return null; 
} 
相关问题