我有3个类似的功能,只根据数字类型改变:
<Extension()> _ Public Function ToNullableShort(ByVal str As String) As Short? Dim intReturn As Short If Short.TryParse(str,intReturn) Then Return intReturn Else Return Nothing End If End Function <Extension()> _ Public Function ToNullableByte(ByVal str As String) As Byte? Dim intReturn As Byte If Byte.TryParse(str,intReturn) Then Return intReturn Else Return Nothing End If End Function <Extension()> _ Public Function ToNullableLong(ByVal str As String) As Long? Dim intReturn As Long If Long.TryParse(str,intReturn) Then Return intReturn Else Return Nothing End If End Function
这里有一个相同的问题(在C#中):
Convert string to nullable type (int,double,etc…)
原文链接:https://www.f2er.com/vb/255249.htmlPublic Function ConvertString(Of T As Structure)(ByVal value As String) As System.Nullable(Of T) Try Return DirectCast(Convert.ChangeType(value,GetType(T)),T) Catch Return Nothing End Try End Function