尝试将c#对象序列化为xml。程序崩溃而不抛出异常

时间:2015-11-18 15:25:57

标签: c# xml

一些背景信息。我使用xsd2code ++从xsd文件生成c#类。当我尝试从该模式序列化一个对象时,程序在该行上崩溃/退出而不抛出异常。我在应用程序的配置文件中遗漏了什么,或者我的视觉工作室是否有错误?当调试器通过“string xml = res.Serialize()”行时,程序就会退出。

/// <summary>
    /// Add the payload to the envelope. The payload is a ReservationService.
    /// </summary>
    /// <param name="env">The envelope</param>
    /// <param name="res">The payload</param>
    /// <returns>The resulting envelope with the payload</returns>
    public static MessageEnvelope AddPayload(MessageEnvelope env, ReservationService res)
    {
        try
        {
            XmlDocument xdoc = new XmlDocument();
            string xml = res.Serialize();
            xdoc.LoadXml(xml);
            env.Payload.Any = xdoc.DocumentElement;
            return env;
        }
        catch(Exception e)
        {
            Trace.TraceError(
                        SetLogString(
                            res.ToString(),
                            "Error",
                            "",
                            e.StackTrace));
        }
        return null;
    }

A first chance exception of type 'System.NullReferenceException' occurred in Communication Service.exe
The thread 0x3e0c has exited with code 259 (0x103).
The thread 0x4194 has exited with code 259 (0x103).
The thread 0x4cc8 has exited with code 259 (0x103).
The thread 0x41bc has exited with code 259 (0x103).
The program '[16160] Communication Service.vshost.exe' has exited with code 0 (0x0).

编辑:添加了输出控制台吐出的一些信息。我想知道为什么它没有陷入try / catch ......

编辑2:在评论中建议的生成的c#文件的顶部添加配置注释。

// ------------------------------------------------------------------------------
//  <auto-generated>
//    Generated by Xsd2Code++. Version 4.0.0.433
//    <NameSpace>Communication.reservation_service</NameSpace><Collection>List</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><GenerateCloneMethod>False</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><DataMemberNameArg>OnlyIfDifferent</DataMemberNameArg><DataMemberOnXmlIgnore>False</DataMemberOnXmlIgnore><CodeBaseTag>Net45</CodeBaseTag><InitializeFields>All</InitializeFields><GenerateUnusedComplexTypes>True</GenerateUnusedComplexTypes><GenerateUnusedSimpleTypes>True</GenerateUnusedSimpleTypes><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableLazyLoading>True</EnableLazyLoading><VirtualProp>False</VirtualProp><PascalCase>False</PascalCase><AutomaticProperties>True</AutomaticProperties><PropNameSpecified>Default</PropNameSpecified><PrivateFieldName>StartWithUnderscore</PrivateFieldName><PrivateFieldNamePrefix></PrivateFieldNamePrefix><EnableRestriction>False</EnableRestriction><RestrictionMaxLenght>False</RestrictionMaxLenght><RestrictionRegEx>False</RestrictionRegEx><RestrictionRange>False</RestrictionRange><ValidateProperty>False</ValidateProperty><ClassNamePrefix></ClassNamePrefix><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>False</EnableSummaryComment><EnableAppInfoSettings>False</EnableAppInfoSettings><EnableExternalSchemasCache>False</EnableExternalSchemasCache><EnableDebug>False</EnableDebug><EnableWarn>False</EnableWarn><ExcludeImportedTypes>True</ExcludeImportedTypes><ExpandNesteadAttributeGroup>True</ExpandNesteadAttributeGroup><CleanupCode>False</CleanupCode><EnableXmlSerialization>True</EnableXmlSerialization><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><EnableEncoding>True</EnableEncoding><EnableXMLIndent>True</EnableXMLIndent><Encoder>UTF8</Encoder><Serializer>XmlSerializer</Serializer><sspNullable>True</sspNullable><sspString>True</sspString><sspCollection>True</sspCollection><sspComplexType>True</sspComplexType><sspSimpleType>True</sspSimpleType><BaseClassName>EntityBase</BaseClassName><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><CustomUsings></CustomUsings><AttributesToExlude></AttributesToExlude>
//  </auto-generated>
// ------------------------------------------------------------------------------

编辑3:正如评论中所建议的那样,我将DebuggerStepTrhough属性移除到xsd2code ++生成的所有类中。 代码退出而不转到finally子句或被捕获到更高的catch子句。当调试器到达“Serializer.Serialize(xmlWriter,this);”时,它会崩溃程序。线。

/// <summary>
        /// Serializes current ReservationService object into an XML string
        /// </summary>
        /// <returns>string XML value</returns>
        public virtual string Serialize(System.Text.Encoding encoding)
        {
            System.IO.StreamReader streamReader = null;
            System.IO.MemoryStream memoryStream = null;
            try
            {
                memoryStream = new System.IO.MemoryStream();
                System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings();
                xmlWriterSettings.Encoding = encoding;
                xmlWriterSettings.Indent = true;
                System.Xml.XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings);
                Serializer.Serialize(xmlWriter, this);
                memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
                streamReader = new System.IO.StreamReader(memoryStream, encoding);
                return streamReader.ReadToEnd();
            }
            finally
            {
                if ((streamReader != null))
                {
                    streamReader.Dispose();
                }
                if ((memoryStream != null))
                {
                    memoryStream.Dispose();
                }
            }
        }

编辑4:问题解决了,由于后台线程完成执行并结束程序,代码中存在一个无关的部分导致程序崩溃/退出。谢谢你的回复。

0 个答案:

没有答案