2

我正在尝试序列化一个包含 EventArgs 对象的对象。如果我在序列化时忽略 EventArgs 对象,一切正常,但如果我不在[XmlIgnore]它上面放置一个,应用程序会崩溃并显示错误消息

System.InvalidOperationException was unhandled
  Message=There was an error generating the XML document.
  Source=System.Xml
  StackTrace:
       at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
       at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces)
       at PullListTesting.SerializeXmlString.ToXml(Object Obj, Type ObjType) in D:\Workspace\MouseKeyboardLibrary\PullListTesting\SerializeXmlString.cs:line 65
       at PullListTesting.frmPickCapture.btnExport_Click(Object sender, EventArgs e) in D:\Workspace\MouseKeyboardLibrary\PullListTesting\frmPickCapture.cs:line 632
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       ...

这是我正在序列化的课程,以及我序列化它的方式:

// <summary>
/// Series of events that can be recorded any played back
/// </summary>
[Serializable]
public class MacroEvent
{
    [XmlAttribute("event-type")]
    public MacroEventType MacroEventType = MacroEventType.NullEvent;

    public EventArgs EventArgs = null;
    public int TimeSinceLastEvent = 0;
    public String Value = null;

    public MacroEvent(){}

    public MacroEvent(MacroEventType macroEventType)
    {
        MacroEventType = macroEventType;
        TimeSinceLastEvent = 1;
    }

    public MacroEvent(MacroEventType macroEventType, EventArgs eventArgs, int timeSinceLastEvent)
    {

        MacroEventType = macroEventType;
        EventArgs = eventArgs;
        TimeSinceLastEvent = timeSinceLastEvent;
    }
}

public static string ToXml(object Obj, System.Type ObjType)
        {

            XmlSerializer ser;
            ser = new XmlSerializer(ObjType, SerializeXmlString.TargetNamespace);
            MemoryStream memStream;
            memStream = new MemoryStream();
            XmlTextWriter xmlWriter;
            xmlWriter = new XmlTextWriter(memStream, Encoding.UTF8);
            xmlWriter.Namespaces = true;
            // VVVVVVV This is where the exception occurs <-------
            ser.Serialize(xmlWriter, Obj, SerializeXmlString.GetNamespaces());
            // ^^^^^^^   This is where the exception occurs <------
            xmlWriter.Close();
            memStream.Close();
            string xml;
            xml = Encoding.UTF8.GetString(memStream.GetBuffer());
            xml = xml.Substring(xml.IndexOf(Convert.ToChar(60)));
            xml = xml.Substring(0, (xml.LastIndexOf(Convert.ToChar(62)) + 1));
            return xml;

        }

我应该如何让 EventArgs 对象正确序列化?

4

0 回答 0