gpt4 book ai didi

c# - 通用 XML 序列化程序

转载 作者:太空宇宙 更新时间:2023-11-03 10:49:05 25 4
gpt4 key购买 nike

我正在尝试按照此处所述实现通用 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);

最佳答案

从类中删除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;
}
}

关于c# - 通用 XML 序列化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22199105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com