我有一个字符串字典,我希望用户能够从中添加/删除信息,然后为他们存储它,以便他们可以在下次程序重新启动时访问它
我不清楚如何将字典存储为设置。我看到在 system.collections.special 下有一个叫做 stringdictionary 的东西,但我读到 SD 已经过时,不应该使用。
同样在未来我可能需要存储一个不仅仅是字符串的字典(int string)
如何在 .net 应用程序的设置文件中存储字典?
最佳答案
您可以使用派生自 StringDictionary 的此类。为了对应用程序设置有用,它实现了 IXmlSerializable。 或者您可以使用类似的方法来实现您自己的 XmlSerializable 类。
public class SerializableStringDictionary : System.Collections.Specialized.StringDictionary, System.Xml.Serialization.IXmlSerializable
{
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
while (reader.Read() &&
!(reader.NodeType == System.Xml.XmlNodeType.EndElement && reader.LocalName == this.GetType().Name))
{
var name = reader["Name"];
if (name == null)
throw new FormatException();
var value = reader["Value"];
this[name] = value;
}
}
public void WriteXml(System.Xml.XmlWriter writer)
{
foreach (System.Collections.DictionaryEntry entry in this)
{
writer.WriteStartElement("Pair");
writer.WriteAttributeString("Name", (string)entry.Key);
writer.WriteAttributeString("Value", (string)entry.Value);
writer.WriteEndElement();
}
}
}
生成的 XML 片段类似于:
...
<setting name="PluginSettings" serializeAs="Xml">
<value>
<SerializableStringDictionary>
<Pair Name="property1" Value="True" />
<Pair Name="property2" Value="05/01/2011 0:00:00" />
</SerializableStringDictionary>
</value>
</setting>
...
关于c# - 在应用程序设置中存储 Dictionary<string,string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/922047/