我有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)?
答案 0 :(得分:10)
这里有一个相同的问题(在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
答案 1 :(得分:3)
怎么样:
Public Shared Function Parse(Of T As Structure)(ByVal value As String) As T?
If String.IsNullOrEmpty(value) Then
Return Nothing
End If
Return New T?(DirectCast(TypeDescriptor.GetConverter(GetType(T)).ConvertFromInvariantString(value), T))
End Function
(注意我用反射器从下面的C#翻译它)
您可以在ConvertFromInvariantString
周围添加try / catch,但说实话,如果我给它一些stoopid,我宁愿让代码抛出异常 - 为空白案例保留空值。
这样做的好处是它可以与您自己的结构一起使用,只要您将类型转换器与它们相关联,您就可以轻松地(使用属性或在运行时)这样做。
public static T? Parse<T>(string value) where T : struct
{
if (string.IsNullOrEmpty(value)) return null;
return (T)TypeDescriptor.GetConverter(typeof(T))
.ConvertFromInvariantString(value);
}