How can I define the type of an XmlSerializer by the type of a record object?
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());
精彩评论