我不确定使用(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