序列化包含字典成員的類別
嘗試序列化包含字典成員的類別(例如設定檔類別)時,可能會遇到以下錯誤:
<code>System.NotSupportedException: 无法序列化成员 App.Configfile.mappedDrives</code>
此錯誤表示預設情況下,Dictionary 類型無法直接序列化。若要解決此問題,請考慮實作自訂序列化機制。
自訂字典序列化
一種方法是建立一個自訂類,該類繼承自 Dictionary<TKey, TValue>
並實作 IXmlSerializable
介面。以下程式碼片段示範了這種實作:
<code class="language-csharp">using System; using System.Collections.Generic; using System.Xml.Serialization; [XmlRoot("dictionary")] public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable { public void ReadXml(System.Xml.XmlReader reader) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); bool wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) return; while (reader.NodeType != System.Xml.XmlNodeType.EndElement) { reader.ReadStartElement("item"); reader.ReadStartElement("key"); TKey key = (TKey)keySerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value"); TValue value = (TValue)valueSerializer.Deserialize(reader); reader.ReadEndElement(); this.Add(key, value); reader.ReadEndElement(); reader.MoveToContent(); } reader.ReadEndElement(); } public void WriteXml(System.Xml.XmlWriter writer) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); foreach (TKey key in this.Keys) { writer.WriteStartElement("item"); writer.WriteStartElement("key"); keySerializer.Serialize(writer, key); writer.WriteEndElement(); writer.WriteStartElement("value"); TValue value = this[key]; valueSerializer.Serialize(writer, value); writer.WriteEndElement(); writer.WriteEndElement(); } } }</code>
透過實作 IXmlSerializable
,自訂字典可以參與 XML 序列化。
用法
定義自訂字典後,可以將其用於在設定檔類別中儲存所需的鍵值對:
<code class="language-csharp">public class ConfigFile { ... public SerializableDictionary<string, string> mappedDrives = new SerializableDictionary<string, string>(); ... }</code>
透過這種方法,可以序列化和反序列化配置文件類,而不會遇到序列化錯誤。
以上是如何序列化設定檔類別中的字典成員?的詳細內容。更多資訊請關注PHP中文網其他相關文章!