有沒有辦法這樣做呢?
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;
}
http://stackoverflow.com/questions/3531318/convert-changetype-fails-on-nullable-types – Eric
有什麼用'沒有在_simply_問題'直接在'Dim b As Boolean? =沒有'? – Sehnsucht
@Sehnsucht它是一個代碼片段。在我的項目中,它可以是每種類型,不僅是'布爾?'。 – user2190035