本文介绍了在设置文件中的关键值存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我开发在C#中,这需要存储在设置文件键值对的应用程序。
我试图想保存设置文件字典的ArrayList,但它没有。这里是我做了什么:
I am developing an application in C#, which needs to store a key value pair in settings file.I tried tried to save an arraylist of dictionary in settings file ,but it fails .Here is what i have done:
if (Settings1.Default.arraylst == null)
{
Settings1.Default.arraylst = new System.Collections.ArrayList();
}
Dictionary<string, string> dd = new Dictionary<string, string>();
dd.Add("1", "1");
Settings1.Default.arraylst.Add(dd);
Settings1.Default.Save();
当我重新启动arrarylist成为空..
When i restarted the application the arrarylist became null..
提前....
推荐答案
这是因为一般的字典不是序列化的一些原因,尝试使用谢谢这个
That's because generic dictionary is not serializable for some reasons,try use this one
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue>
: Dictionary<TKey, TValue>, 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
}
这是我在这里找到
这篇关于在设置文件中的关键值存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!