Cra*_*893 33 c# settings dictionary .net-3.5
我有一个字符串字典,我希望用户能够添加/删除信息然后存储它们,以便他们可以在下次程序重新启动时访问它
我不知道如何将字典存储为设置.我看到在system.collections.special下有一个叫做stringdictionary的东西,但我读过SD已经过时了,不应该使用它.
同样在将来我可能需要存储一个不仅仅是字符串的字典(int string)
如何在.net应用程序的设置文件中存储字典?
Vse*_*nov 43
您可以使用从StringDictionary派生的此类.为了对应用程序设置有用,它实现了IXmlSerializable.或者您可以使用类似的方法来实现自己的XmlSerializable类.
public class SerializableStringDictionary : StringDictionary, IXmlSerializable
{
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
while (reader.Read() &&
!(reader.NodeType == 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(XmlWriter writer)
{
foreach (DictionaryEntry entry in this)
{
writer.WriteStartElement("Pair");
writer.WriteAttributeString("Name", (string)entry.Key);
writer.WriteAttributeString("Value", (string)entry.Value);
writer.WriteEndElement();
}
}
}
Run Code Online (Sandbox Code Playgroud)
生成的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>
...
Run Code Online (Sandbox Code Playgroud)
Dav*_*vid 16
最简单的答案是使用行和列分隔符将字典转换为单个字符串.然后你只需要在设置文件中存储1个字符串.
| 归档时间: |
|
| 查看次数: |
39114 次 |
| 最近记录: |