是否可以使共享功能通用?

时间:2011-02-16 12:32:08

标签: vb.net generics

我可以create classes that use generics,但我想知道是否可以将此应用于共享方法,而不是依赖于调用者强制转换为正确的类型。

这是方法:

Public Shared Function DeserializeObject(ByVal serializedXml As String, ByVal givenType As System.Type) As Object
    Dim serializer As New XmlSerializer(givenType)
    Return serializer.Deserialize(New IO.StringReader(serializedXml))
End Function

我很确定这不可能做到,但我想我会检查一下(如果有人可以在技术上解释为什么编译器不能这样做的话,那么会给予额外积分)。替代建议也是赞赏。

3 个答案:

答案 0 :(得分:3)

没有理由你无法创建该函数的通用版本。 e.g:

Public Shared Function Deserialize(Of T)(ByVal serializedXml As String) As T
    Dim serializer As New XmlSerializer(GetType(T))
    Return DirectCast(serializer.Deserialize(New StringReader(serializedXml)), T)
End Function

答案 1 :(得分:3)

Public Shared Function StronglyTypedDeserializeObject(Of T)
       (ByVal serializedXml As String) As T

    Dim serializer As New XmlSerializer(GetType(T))

    Return DirectCast(
              serializer.Deserialize(New IO.StringReader(serializedXml))
              , T)

End Function

请注意,调用必须提供预期的类型:

Dim foo As MyType 
    = Utility.StronglyTypedDeserializeObject(Of MyType)(sourceXml)

答案 2 :(得分:-1)

以下示例显示了如何执行此操作。唯一的技巧是记住,你可以使用GetType函数定义Generic,例如GetType(MyObject(Of T))

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim Test1 As New MyObject(Of String)
        Dim Test2 As New MyObject(Of Integer)
        Dim Data As String = ""
        Test1.Data = "Hello World"
        Test2.Data = 1010101

        Data = Test1.SerializeObject
        Test1 = MyObject(Of String).DeserializeObject(Data)
        Debug.Print(Test1.Data)

        Data = Test2.SerializeObject
        Test2 = MyObject(Of Integer).DeserializeObject(Data)
        Debug.Print(Test2.Data)
    End Sub

End Class

Public Class MyObject(Of T)
    Public Data As T

    Public Sub New()
    End Sub

    Public Shared Function DeserializeObject(ByVal serializedXml As String) As MyObject(Of T)
        Dim serializer As New XmlSerializer(GetType(MyObject(Of T)))
        Return serializer.Deserialize(New IO.StringReader(serializedXml))
    End Function

    Public Function SerializeObject() As String
        Dim serializer As New XmlSerializer(GetType(MyObject(Of T)))
        Dim Result As New IO.StringWriter()
        serializer.Serialize(Result, Me)
        Return Result.ToString
    End Function
End Class

如果你不喜欢完全限定类型以获得共享成员,那么你可以做这样的事情。

Public Class MyObjectString
    Inherits MyObject(Of String)
End Class

然后你可以调用MyObjectString.Deserialize