0

我有一个奇怪的例外:

System.InvalidOperationException:生成 XML 文档时出错。---> System.NullReferenceException:对象引用未设置为对象的实例。在 Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterRules.XSArrayInfo.get_Item(Object a, Int32 i) 在 Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterRules.Write5_SearchAndReturnRules(String n, String ns, Object o, Boolean isNullable, Boolean needType) 在Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterRules.Write6_SearchAndReturnRules(Object o)
--- 内部异常堆栈跟踪结束 ---
在 System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id) at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces) 在 MergeExcelFilesForm.SaveSearchRulesToFile (StreamWriter 流)

 using (var streamWriter = new StreamWriter(saveFileDialog.FileName))
 {
       SaveSearchRulesToFile(streamWriter);
 }

 public void SaveSearchRulesToFile(StreamWriter stream)
 {
       var rules = GetRules();
       var rulesSerializer = new XmlSerializer(rules.GetType());
       rulesSerializer.Serialize(stream, rules);
 }

序列化类非常简单,没有特殊属性(只给出主类,不要认为子类很重要,因为它们更简单):

 public class Rules
 {
    public List<SearchRule> SearchRules { get; set; }
    public List<CopyRule> CopyRules { get; set; }
    public int SourceHeaderRow { get; set; }
    public int DestinationHeaderRow { get; set; }
 } 


public class SearchRule
{
    public HeaderItem SearchFor { get; set; }
    public HeaderItem SearchIn { get; set; }

    public SearchRule()
    {            
    }

    public SearchRule(int indexFor, int indexIn)
    {
        SearchFor = new HeaderItem(indexFor);
        SearchIn = new HeaderItem(indexIn);
    }
}

public class HeaderItem
{
    public HeaderItem()
    {            
    }

    public HeaderItem(int columnIndex, string displayName)
    {
        ColumnIndex = columnIndex;
        DisplayName = displayName;
    }

    public HeaderItem(int columnIndex) : this(columnIndex, columnIndex.ToString())
    {            
    }

    public string DisplayName { get; set; }
    public int ColumnIndex { get; set; }

    public override string ToString()
    {
        return DisplayName;
    }
}

现在有趣的部分 - 安装 .NET 4.5 时它运行良好,如果目标机器上只有 .NET 4.0 则失败,目标平台是 .NET 4.0。

4

1 回答 1

3

您可以使用以下命令调试 XML 序列化进程:

<system.diagnostics>
    <switches>
        <add name="XmlSerialization.Compilation" value="1" />
    </switches>
</system.diagnostics>

生成的源类位于本地临时文件夹中。因此,您可以轻松地逐步完成解析内容,并可能在您的 XML 文件中检测到问题。

于 2012-08-24T10:09:00.310 回答