gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:35:46 27 4
gpt4 key购买 nike

我有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

关于.net - 创建将字符串转换为可为空的数字的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1019346/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com