2015-05-29 50 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; 
} 
相關問題