.net – 创建将字符串转换为可空数字的通用方法

前端之家收集整理的这篇文章主要介绍了.net – 创建将字符串转换为可空数字的通用方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有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

我试图用这个来制作一个泛型函数,但是无法做到.如何创建一个通用函数获取特定的T并使其成为Nullable(T)?

这里有一个相同的问题(在C#中): Convert string to nullable type (int,double,etc…)
Public 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

猜你在找的VB相关文章