如何通过记录对象的类型定义XmlSerializer的类型?

时间:2011-02-08 02:00:12

标签: c# .net xml-serialization

下面的代码问题,在这一行:

XmlSerializer x = new XmlSerializer(typeof(????)); 

我希望记录对象定义类型,我可以这样做吗?

public void ConvertRecordObjectToXML(object RecordObject, out string XML) 
{
    string xml = string.Empty;

    try
    {
        string XmlizedString = null;
        MemoryStream memoryStream = new MemoryStream();
        XmlSerializer x = new XmlSerializer(typeof(????)); // <---- ?????
        XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

        x.Serialize(xmlTextWriter, RecordObject);
        memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
        XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
        XML = XmlizedString;
    }
    catch (Exception e)
    {
        System.Console.WriteLine(e);
        xml = "";
    }
}

2 个答案:

答案 0 :(得分:6)

每个对象都从Object继承GetType()方法,因此您应该能够使用:

XmlSerializer x = new XmlSerializer(RecordObject.GetType());

C# typeof 关键字获取类名并生成Type类型的对象。 GetType()产生相同的东西,但改为在实例上运行。

答案 1 :(得分:3)

你试过这个吗?

XmlSerializer x = new XmlSerializer(RecordObject.GetType());