簡體   English   中英

帶有IXmlSerializable的自定義類因OutOfMemoryException而失敗

[英]Custom class with IXmlSerializable fails with OutOfMemoryException

我有以下xml文件:

<MyConfig>
  <Item a1="Attrib11" a2="Attrib21" a3="Attrib31" />
  <Item a1="Attrib12" a2="Attrib22" a3="Attrib32" />
</MyConfig>

我使用以下幫助器方法加載它:

public static T Load<T>(string path)
{
    XmlSerializer xml = new XmlSerializer(typeof(T));

    using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
    using (StreamReader sr = new StreamReader(fs))
    {
        return (T)xml.Deserialize(sr);
    }
}

public static void Save<T>(string path, T contents)
{
    XmlSerializer xml = new XmlSerializer(typeof(T));

    using (FileStream fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
    using (StreamWriter sw = new StreamWriter(fs))
    {
        xml.Serialize(sw, contents, ns);
    }
}

這是MyConfig

public class MyConfig
{
    [XmlElement("Item")]
    public List<Item> Items { get; set; }

    public MyConfig()
    {
        Items = new List<Item>();
    }
}

public class Item : IXmlSerializable
{
    [XmlAttribute()]
    public string Attrib1 { get; set; }

    [XmlAttribute()]
    public string Attrib2 { get; set; }

    [XmlAttribute()]
    public string Attrib3 { get; set; }

    public Item(string attrib1, string attrib2, string attrib3)
    {
        Attrib1 = attrib1;
        Attrib2 = attrib2;
        Attrib3 = attrib3;
    }

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        if (reader.MoveToContent() == XmlNodeType.Element)
        {
            Attrib1 = reader.GetAttribute("a1");
            Attrib2 = reader.GetAttribute("a2");
            Attrib3 = reader.GetAttribute("a3");
        }
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteAttributeString("a1", Attrib1);
        writer.WriteAttributeString("a2", Attrib2);
        writer.WriteAttributeString("a3", Attrib3);
    }
}

然后我有以下測試床代碼來檢查類的序列化:

string file = "somePath";

MyConfig myConfig = new MyConfig()
{
    Items = new List<Item>()
    {
        new Item("Attrib11", "Attrib21", "Attrib31"),
        new Item("Attrib12", "Attrib22", "Attrib32"),
    },
};

Save(file, myConfig);

MyConfig myConfig2 = Load<MyConfig>(file);

這在Load時出現OutOfMemory異常失敗,我該如何解決這個問題? 檢查somePath的文件,看起來是正確的。

在閱讀完屬性后,您需要告訴reader前進到下一個節點:

public void ReadXml(XmlReader reader)
{
    if (reader.MoveToContent() == XmlNodeType.Element)
    {
        Attrib1 = reader.GetAttribute("a1");
        Attrib2 = reader.GetAttribute("a2");
        Attrib3 = reader.GetAttribute("a3");
    }
    // Go to the next node.
    reader.Read();
}

如果你不調用reader.Read()reader會一遍又一遍地讀取同一個節點,因此XmlSerializer將創建無限量的Item實例,直到你最終得到OutOfMemoryException

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM