使用泛型类型来创建该对象的新实例

时间:2014-05-21 13:40:43

标签: vb.net object generics

我对Generics很新,虽然我对它有一些疑问,但看起来对我的问题很有希望。

我正在构建一个通用函数,它将xml反序列化为一个对象,然后创建该对象的ArrayList并将其返回。

我的问题是如何实施仿制药呢?为了更清楚,我需要创建 new 对象实例并为其属性赋值。

这是我的功能:

Private Function DeSerializeArrayList(serializedData As String, ByVal ObjectName As Object, ByVal ObjType As System.Type, ByVal ReturnObjectType As System.Type) As ArrayList
    Dim list As New ArrayList()
    Dim extraTypes As Type() = New Type(0) {}

    extraTypes(0) = ObjectName.GetType()
    'Code fails here and says can't include anonymous class
    Dim serializer As New System.Xml.Serialization.XmlSerializer(ObjectName.GetType(), extraTypes)

    Dim xReader As XmlReader = XmlReader.Create(New StringReader(serializedData))

    Try
        Dim obj = serializer.Deserialize(xReader)

        For i As Integer = 0 To obj.Items.Length - 1
            'Need to create NEW object
            Dim labPrice As Type() = New Type(0) {}
            labPrice(0) = ReturnObjectType

            'Need some method to get the properties of that object
            'Dim s = labPrice(0).GetEnumNames

            'Need to asign values to that object's properties
            'With labPrice
            '    .fLabPricelistID = obj.Items(i).fLabPricelistID
            '    .ftariffCode = obj.Items(i).fTariffCode
            '    .fSurfaced = obj.Items(i).fSurfaced
            '    .fLabCostPrice = obj.Items(i).fLabCostPrice
            '    .fLabDiscountedPrice = obj.Items(i).fLabDiscountedPrice
            '    .fEffectiveDate = obj.Items(i).fEffectiveDate
            '    .fLaboratoryCodeID = obj.Items(i).fLaboratoryCodeID
            '    .fDescription = obj.Items(i).fDescription
            '    .flabProduct = obj.Items(i).fLabProduct
            '    .fActive = obj.Items(i).fActive
            'End With

            'list.Add(labPrice)
        Next
    Catch
        Throw
    Finally
        xReader.Close()
    End Try

    Return list

End Function

1 个答案:

答案 0 :(得分:0)

我找到了一个完全符合我的问题的解决方案:

Dim obj = DeserializeObject(Of TestObject)(xmlString)

'Function will map xml to object/list of objects
Public Function DeserializeObject(Of T)(xml As String) As T
    Dim xs As New XmlSerializer(GetType(T))
    Dim memoryStream As New MemoryStream(StringToUTF8ByteArray(xml))
    Dim xmlTextWriter As New XmlTextWriter(memoryStream, Encoding.UTF8)

    Dim obj = DirectCast(xs.Deserialize(memoryStream), T)
    Return obj
End Function

Public Shared Function StringToUTF8ByteArray(stringVal As String) As [Byte]()
    Dim encoding As New UTF8Encoding()
    Dim byteArray As Byte() = encoding.GetBytes(stringVal)
    Return byteArray
End Function