我不確定使用(Of T)
使用泛型函數和使用類型參數returnType As Type
之間的區別是什麼,對於將JSON字符串轉換爲Object子類型的函數最佳方法如下所示。VB.NET:使用類型參數vs使用泛型函數?
Visual Studio抱怨當我嘗試訪問其預先知道其子類型的對象的屬性,以及試圖將對象轉換爲所需的子類型時。但是,只有在使用通用函數方法時纔會這樣做。
我需要的函數簽名是足夠通用的,以便它可以包含在多個類的接口中以便稍後實現。
Public Overloads Function Execute(jsonData As String, returnType As Type) As Object Implements IHandler.Execute
' Deserializes the JSON to the specified .NET type.
Dim result = JsonConvert.DeserializeObject(jsonData, returnType)
' Visual Studio does not complain, and the function still works
' without the need of explicitly converting and checking:
' result = TryCast(result, Response)
' If result Is Nothing Then
' Throw New Exception("Conversion failed")
' End If
' Visual Studio does not complain:
if result.Success Then
ProcessMessage(result.Message)
ElseIf result.Errors.length > 0 Then
HandleErrors(result.Errors)
End If
Return result
End Function
Public Overloads Function Execute(Of T)(jsonData As String) As T Implements IHandler.Execute
' Deserializes the JSON to the specified .NET type.
Dim result = JsonConvert.DeserializeObject(Of T)(jsonData)
' Visual Studio complains:
result = TryCast(result, Response)
If result Is Nothing Then
Throw New Exception("Conversion failed")
End If
' Visual Studio complains:
if result.Success Then
ProcessMessage(result.Message)
ElseIf result.Errors.length > 0 Then
HandleErrors(result.Errors)
End If
Return result
End Function
什麼是最好的辦法,就是兩者之間的差異,以及爲什麼Visual Studio中抱怨使用通用的做法,但經過類型作爲參數時,不會抱怨什麼時候?
我使用Newtonsoft.Json
框架中的JsonConvert
類。
參考:http://www.newtonsoft.com/json/help/html/Overload_Newtonsoft_Json_JsonConvert_DeserializeObject.htm
在泛型函數:什麼是dataResult?您正在反序列化一個對象,但實際上並未使用它,因爲您覆蓋了(未知?)dataresult轉換的結果。 –
@RuardvanElburg這不是一個嚴重的錯誤。它應該是「結果」,但遺憾的是,這與解決方案無關。我稍後添加了部分代碼來嘗試進一步突出顯示問題,並將其錯誤地輸入。不管怎樣,感謝您的注意。 – Mayron