Csharp/C#教程:设置文件中的键值存储分享


设置文件中的键值存储

我正在用C#开发一个应用程序,它需要在设置文件中存储一个键值对。 我尝试在设置文件中保存字典的arraylist,但它失败了。这就是我所做的:

if (Settings1.Default.arraylst == null) { Settings1.Default.arraylst = new System.Collections.ArrayList(); } Dictionary dd = new Dictionary(); dd.Add("1", "1"); Settings1.Default.arraylst.Add(dd); Settings1.Default.Save(); 

当我重新启动应用程序时,arrarylist变为null。

提前致谢….

这是因为通用字典由于某些原因不可序列化,请尝试使用此字典

 using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; [XmlRoot("dictionary")] public class SerializableDictionary : Dictionary, IXmlSerializable { #region IXmlSerializable Members public System.Xml.Schema.XmlSchema GetSchema() { return null; } 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(); } } #endregion } 

我在这里找到了XML Serializable Generic Dictionary

C#设置文件只是XML文件,只保存可序列化的类,否则保存时不会写出数据。 遗憾的是,词典不可序列化。

一种解决方案是构建自己的包装器,以正确序列化字典。 这个链接可以让您了解这涉及到什么。

另一种解决方案是将键/值对写为长字符串数组,并在重新读取时解析它。

 //Define a string[] in your settings List keyValues = new List(); foreach(KeyValuePair pair in dd) { keyValues.Add(pair.Key); keyValues.Add(pair.Value); } Settings1.Default.KeyValuePairs = keyValues.ToArray(); 

然后在以类似方式加载时回读对。

上述就是C#学习教程:设置文件中的键值存储分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1029162.html

(0)
上一篇 2022年1月12日
下一篇 2022年1月12日

精彩推荐