2017-06-12 84 views
1

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

+0

在泛型函数:什么是dataResult?您正在反序列化一个对象,但实际上并未使用它,因为您覆盖了(未知?)dataresult转换的结果。 –

+0

@RuardvanElburg这不是一个严重的错误。它应该是“结果”,但遗憾的是,这与解决方案无关。我稍后添加了部分代码来尝试进一步突出显示问题,并将其错误地输入。不管怎样,感谢您的注意。 – Mayron

回答

0

有多种原因,编译器会抱怨的通用功能,但它无关,与被仿制。

首先,结果变量是T类型:

Dim result = JsonConvert.DeserializeObject(Of T)(jsonData) 

我不认为result.Successresult.Errors在T.定义所以很明显,编译器会抱怨了一番。 如果你想使用这些函数,那么不要使用T而是使用Response。

而且您要转换的变量结果反应(这是T类型):

result = TryCast(result, Response) 

你可以不投结果输入响应的结果是一个类型T的则应该是:

result = TryCast(result, T) 

但你并不需要这个说法,因为在所有的结果已经被铸造到T.

一般情况下:如果你没有不使用对象。使用通用函数。始终使用最具体的类型。

调用具有指定类型的功能:执行(响应)(jsonData)或更改功能:

Public Overloads Function Execute(jsonData As String) As Response Implements IHandler.Execute 
    Dim result = JsonConvert.DeserializeObject(Of Response)(jsonData) 
+0

我绝对需要使函数泛型或声明正在使用的类型。但是使用'Execute(Of Response)(jsonData)'不起作用,因为我需要编写的代码体(来自实现泛型函数的类)依赖于特定的类型,这就是为什么我需要将它转换为正确的类型。 我只是不确定为什么一种方法有效,但另一种方法没有。 – Mayron

+0

你可以使用一个接口。将结果转换为具有所需属性的接口。 –

+0

我现在没有时间举一个例子。我会尽量在今天晚些时候更新我的答案。 –

相关问题