我想寫一個典型的函數的重載,我的意圖是完成調用一個函數的兩個任務(當然優化代碼以更好的方式和幾行代碼完成任務,我不知道我的方法應該是更好的方式,但這是我想要的):試圖編碼'字符串是數字的類型?'方法通過反射
1st:確定字符串值是否爲數字。
2nd:確定數值是否爲apropiate DataType。 (整數,長,等...) 長,等...)
但我有兩個問題:
1:方法 「的TryParse」 上沒有找到反射搜索(我嘗試了很多綁定組合)。
第二:我不知道如何實例的方法 參數的數據類型(參見:
{Value, New T}
)
這裏是我的代碼:
Private Function StringIsNumericOf(Of T)(ByVal Value As String) As Boolean
Dim Method As MethodInfo =
GetType(T).GetMethod("TryParse", BindingFlags.Public)
If Method IsNot Nothing Then
Return Method.Invoke(Me, BindingFlags.Public, Nothing,
New Object() {Value, New T},
CultureInfo.InvariantCulture)
Else
MsgBox("Method not found.")
Return Nothing
End If
End Function
而且這裏有一個例子使用我想什麼樣的期待:
' Expected result: False, it's a Double.
MsgBox(StringIsNumericOf(Of Long)("50.1D"))
' Expected result: False, it's an Int64.
MsgBox(StringIsNumericOf(Of Integer)("1L"))
' Expected result: True
MsgBox(StringIsNumericOf(Of Long)(CStr(Long.MaxValue)))
UPDATE:
只是失敗意圖解決的第一個問題,這就是我努力:
Dim Method As MethodInfo =
GetType(T).GetMethod("TryParse",
BindingFlags.Public Or BindingFlags.Static,
Type.DefaultBinder,
New Type() {GetType(String), GetType(T)},
New ParameterModifier() {})
當搜索'TryParse'時,是否包含'Static'綁定標誌? - TryParse是類型上的靜態方法,並用作Integer.TryParse(...' –
@Jon Egerton我沒有試過那個標誌,現在有了你的幫助,我能夠找到這個方法,但是它會拋出一個異常,說找到了一個模糊的方法匹配,我想這是因爲TryParse方法有一個超負荷,但如何解決呢? – ElektroStudios