开发者

How can I define the type of an XmlSerializer by the type of a record object?

开发者 https://www.devze.com 2023-02-09 18:12 出处:网络
Problem with the code below, on this line: XmlSerializer x = new XmlSerializer(typeof(????)); I want the type to be define by the record object, can I do that?

Problem with the code below, on this line:

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

I want the type to be define by the record object, can I do that?

public void ConvertRecordObjectToXML(object RecordObjec开发者_Go百科t, 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 = "";
    }
}


Every object inherits the method GetType() from Object, so you should be able to use:

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

The C# typeof keyword takes the class name and yields an object of type Type. GetType() yields the same thing, but operates on an instance instead.


Have you tried this?

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

精彩评论

暂无评论...
验证码 换一张
取 消