VB.NET,使用返回类型泛型函数?

时间:2010-04-29 09:08:05

标签: c# xml vb.net xml-serialization

目前我编写了一个反序列化XML的函数,如下所示。 如何更改它,以便每次我想要序列化另一个对象类型时都不必替换类型?当前对象类型是cToolConfig。如何使此功能通用?

       Public Shared Function DeserializeFromXML(ByRef strFileNameAndPath As String) As XMLhandler.XMLserialization.cToolConfig
        Dim deserializer As New System.Xml.Serialization.XmlSerializer(GetType(cToolConfig))
        Dim srEncodingReader As IO.StreamReader = New IO.StreamReader(strFileNameAndPath, System.Text.Encoding.UTF8)
        Dim ThisFacility As cToolConfig

        ThisFacility = DirectCast(deserializer.Deserialize(srEncodingReader), cToolConfig)
        srEncodingReader.Close()
        srEncodingReader.Dispose()

        Return ThisFacility
    End Function


    Public Shared Function DeserializeFromXML1(ByRef strFileNameAndPath As String) As System.Collections.Generic.List(Of XMLhandler.XMLserialization.cToolConfig)
        Dim deserializer As New System.Xml.Serialization.XmlSerializer(GetType(System.Collections.Generic.List(Of cToolConfig)))
        Dim srEncodingReader As IO.StreamReader = New IO.StreamReader(strFileNameAndPath, System.Text.Encoding.UTF8)
        Dim FacilityList As System.Collections.Generic.List(Of cToolConfig)
        FacilityList = DirectCast(deserializer.Deserialize(srEncodingReader), System.Collections.Generic.List(Of cToolConfig))
        srEncodingReader.Close()
        srEncodingReader.Dispose()

        Return FacilityList
    End Function

1 个答案:

答案 0 :(得分:5)

这是你的意思吗?

Public Shared Function DeserializeFromXML(Of T)(ByRef strFileNameAndPath As String) As T
    Dim deserializer As New System.Xml.Serialization.XmlSerializer(GetType(T))
    Dim srEncodingReader As IO.StreamReader = New IO.StreamReader(strFileNameAndPath, System.Text.Encoding.UTF8)
    Dim ThisFacility As T

    ThisFacility = DirectCast(deserializer.Deserialize(srEncodingReader), T)
    srEncodingReader.Close()
    srEncodingReader.Dispose()

    Return ThisFacility
End Function


Public Shared Function DeserializeFromXML1(Of T)(ByRef strFileNameAndPath As String) As System.Collections.Generic.List(Of T)
    Dim deserializer As New System.Xml.Serialization.XmlSerializer(GetType(System.Collections.Generic.List(Of T)))
    Dim srEncodingReader As IO.StreamReader = New IO.StreamReader(strFileNameAndPath, System.Text.Encoding.UTF8)
    Dim FacilityList As System.Collections.Generic.List(Of T)
    FacilityList = DirectCast(deserializer.Deserialize(srEncodingReader), System.Collections.Generic.List(Of T))
    srEncodingReader.Close()
    srEncodingReader.Dispose()

    Return FacilityList
End Function

请注意,您可以在T上设置约束,例如:

Public Shared Function DeserializeFromXML(Of T As Class)

甚至提出了多个约束,例如:

Public Shared Function DeserializeFromXML(Of T As {Class, New, IDisposable})