Основные функции работаю, не могу разобраться с кешированием объекта сериализации (функци GetSerializer)
Что я делаю неправильно?
- Код: Выделить всё
Public Class XmlUtility
Private Shared _Hash As New Hashtable
Public Shared Function GetSerializer(ByVal pType As Type) As XmlSerializer
Dim _Res As XmlSerializer
SyncLock _Hash
_Res = _Hash(pType.FullName)
If Not (_Res Is Nothing) Then
_Res = New XmlSerializer(pType)
_Hash(pType.FullName) = _Res
End If
End SyncLock
Return _Res
End Function
Public Shared Function Obj2XmlStr(ByVal pObject As Object, ByVal pNameSpace As String) As String
If Not pObject Is Nothing Then
Dim Sr As New XmlSerializer(pObject.GetType) 'SerializerCache.GetSerializer(type)
Dim Sb As New StringBuilder
Dim W As New StringWriter(Sb, System.Globalization.CultureInfo.InvariantCulture)
Sr.Serialize(W, pObject, New XmlSerializerNamespaces(New XmlQualifiedName() {New XmlQualifiedName("", pNameSpace)}))
Return Sb.ToString
End If
Return String.Empty
End Function
Public Shared Function Obj2XmlStr(ByVal pObject As Object) As String
If Not pObject Is Nothing Then
Dim Sr As New XmlSerializer(pObject.GetType) 'SerializerCache.GetSerializer(type)
Dim Sb As New StringBuilder
Dim W As New StringWriter(Sb, System.Globalization.CultureInfo.InvariantCulture)
Sr.Serialize(W, pObject, New XmlSerializerNamespaces(New XmlQualifiedName() {New XmlQualifiedName(String.Empty)}))
Return Sb.ToString
End If
Return String.Empty
End Function
Public Shared Function Xml2Obj(Of T)(ByVal pXmlStream As Stream) As T
If pXmlStream Is Nothing Then
Return DirectCast(Activator.CreateInstance(GetType(T)), T)
End If
Dim Sr As XmlSerializer = GetSerializer(GetType(T))
'Dim Sr As New XmlSerializer(GetType(T)) ' <-- рабочий код!!!
Return DirectCast(Sr.Deserialize(pXmlStream), T)
End Function
Public Shared Function Xml2Obj(Of T)(ByVal pFileName As String) As T
Dim _Obj As T
Using _Stream As IO.Stream = File.OpenRead(pFileName)
_Obj = Xml2Obj(Of T)(_Stream)
End Using
Return _Obj
End Function
End Class