我正在尝试实现如下所述的通用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/

10-12 15:27