我正在尝试实现此处所述的通用XML序列化程序: http://blogs.msdn.com/b/field_notes/archive/2008/06/19/the-last-datacontract-serializer-on-earth.aspx
internal static class GenericXmlSerializer<T>
{
public static void WriteObject(T outputObject, string outputFile)
{
using (FileStream writer = new FileStream(outputFile, FileMode.Create))
{
XmlSerializer ser = new XmlSerializer(typeof(T));
ser.Serialize(writer, outputObject);
}
}
public static T ReadObject(string objectData)
{
T deserializedObject = default(T);
using (StringReader reader = new StringReader(objectData))
{
XmlTextReader xmlReader = new XmlTextReader(reader);
XmlSerializer ser = new XmlSerializer(typeof(T));
deserializedObject = (T)ser.Deserialize(xmlReader);
xmlReader.Close();
}
return deserializedObject;
}
}
然后我想打电话给它,但我不想硬编码我的对象类型(例如硬编码):
GenericXmlSerializer<MyObjectType>.WriteObject((MyObjectType)data.Payload ,stream);
如何在运行时获取这些对象类型? 例如类似的东西:
GenericXmlSerializer<typeof(data.Payload)>.WriteObject((MyObjectType)data.Payload ,stream);
答案 0 :(得分:2)
从课程中删除T
,然后您可以使用
GenericXmlSerializer.WriteObject(anyObject,"a.xml");
internal static class GenericXmlSerializer
{
public static void WriteObject<T>(T outputObject, string outputFile)
{
using (FileStream writer = new FileStream(outputFile, FileMode.Create))
{
XmlSerializer ser = new XmlSerializer(typeof(T));
ser.Serialize(writer, outputObject);
}
}
public static T ReadObject<T>(string objectData)
{
T deserializedObject = default(T);
using (StringReader reader = new StringReader(objectData))
{
XmlTextReader xmlReader = new XmlTextReader(reader);
XmlSerializer ser = new XmlSerializer(typeof(T));
deserializedObject = (T)ser.Deserialize(xmlReader);
xmlReader.Close();
}
return deserializedObject;
}
}
答案 1 :(得分:0)
我写的vb.net
的通用XML SerializerImports System.IO
Imports System.Text
Imports System.Xml
Imports System.Xml.Serialization
Friend Module XML
Public Function Deserialize(Of T)(ByVal filename As String) As T
Dim result As T
Using reader As New StreamReader(filename, True)
Dim serializer As New XmlSerializer(GetType(T))
result = CType(serializer.Deserialize(XmlReader.Create(reader)), T)
End Using
Return result
End Function
Public Sub Serialize(Of T)(ByVal filename As String, ByVal obj As T, ByVal qualifiedNames As XmlQualifiedName(), ByVal encoding As Encoding)
Dim namespaces As New XmlSerializerNamespaces(qualifiedNames)
Dim settings = New System.Xml.XmlWriterSettings()
settings.Encoding = encoding
Dim serializer = New XmlSerializer(GetType(T))
Using writer = XmlWriter.Create(filename, settings)
writer.WriteStartDocument(True)
serializer.Serialize(writer, obj, namespaces)
End Using
End Sub
End Module