在.NET中,您可以选择哈希表作为用户设置的类型。但是当我保存并以这种方式检索它时,它似乎根本没有保存它。
Hashtable t = new Hashtable();
t.Add(1,"Foo");
t.Add(2,"Bar");
Properties.Settings.Default.Setting = t;
Properties.Settings.Default.Save();
if(Properties.Settings.Default.Setting != null)
foreach (DictionaryEntry entry in Properties.Settings.Default.Setting)
{
MessageBox.Show(entry.Key + " " + entry.Value);
}
为什么它不能在用户设置中序列化,当我可以在Visual Studio中清楚地选择该类型时?我会理解,如果这是一个未列出的类型,如字典,但列出了Hashtable。我该如何解决这个问题呢? 这个顺序的简单性和效率对我来说是最重要的。
非常感谢, 卡瓦
更新
@Joao,非常感谢二元解决方案。我发现它很有趣,很干净。将其序列化为二进制文件的一个disadvavtage可能是您不能再手动更改usersetting文件中的任何内容。但我认为无论如何都会很少这样做,所以这是一个很好的解决方案。
我在考虑在用户范围内创建字符串类型的“XMLSetting”字段的不同方法,并使用此代码将值存储和检索为序列化为哈希表的XMl文件。但我确信这不是最好的方法,有没有人知道在用户设置中将哈希表/字典序列化为xml的更好方法,除了我在下面做的事情?
if(string.IsNullOrEmpty(Properties.Settings.Default.XMLSetting))
{
Console.WriteLine("Usersettings is empty. Initializing XML file...");
XmlDocument doc = new XmlDocument();
XmlElement hashtable = doc.CreateElement("HashTable");
doc.AppendChild(hashtable);
GenerateValues(doc, hashtable, "1", "Foo");
GenerateValues(doc, hashtable, "2", "Bar");
Properties.Settings.Default.XMLSetting = doc.OuterXml;
Properties.Settings.Default.Save();
}
else
{
Console.WriteLine("Retrieving existing user settings...");
XmlDocument doc = new XmlDocument();
doc.LoadXml(Properties.Settings.Default.XMLSetting);
Hashtable hashtable = new Hashtable();
foreach (XmlNode entry in doc.DocumentElement.ChildNodes)
{
hashtable.Add(int.Parse(entry.FirstChild.InnerText), entry.FirstChild.NextSibling.InnerText);
}
foreach (DictionaryEntry entry in hashtable)
{
Console.WriteLine(entry.Key + " " + entry.Value);
}
}
private static void GenerateValues(XmlDocument doc, XmlElement hashtable, string skey, string svalue)
{
XmlElement entry = doc.CreateElement("entry");
XmlElement key = doc.CreateElement("Key");
XmlElement value = doc.CreateElement("Value");
entry.AppendChild(key);
entry.AppendChild(value);
key.AppendChild(doc.CreateTextNode(skey));
value.AppendChild(doc.CreateTextNode(svalue));
hashtable.AppendChild(entry);
}
答案 0 :(得分:12)
Hashtable不支持序列化为XML,也不支持简单的字符串。这些是使用Settings.settings文件和关联的自动生成的类时可用的两个序列化选项。
但是,如果您自己创建设置类并管理App.Config部分,则可以使用二进制序列化来保留Hastable。
请参阅以下示例。这是一个包含以下文件的控制台应用程序:
的App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup
name="userSettings"
type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section
name="ConsoleApplication1.MyCustomSettings"
type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
allowExeDefinition="MachineToLocalUser"
requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<ConsoleApplication1.MyCustomSettings>
<setting name="MyHashtable" serializeAs="Binary">
<value></value>
</setting>
<setting name="MyBackColor" serializeAs="String">
<value>Silver</value>
</setting>
</ConsoleApplication1.MyCustomSettings>
</userSettings>
</configuration>
手动创建的自定义设置类:
public class MyCustomSettings : ApplicationSettingsBase
{
private static MyCustomSettings defaultInstance = (
(MyCustomSettings)
(ApplicationSettingsBase.Synchronized(new MyCustomSettings())));
public static MyCustomSettings Default
{
get { return defaultInstance; }
}
[UserScopedSettingAttribute()]
[DebuggerNonUserCodeAttribute()]
[DefaultSettingValueAttribute("Silver")]
public Color MyBackColor
{
get { return ((Color)(this["MyBackColor"])); }
set { this["MyBackColor"] = value; }
}
[UserScopedSettingAttribute()]
[DebuggerNonUserCodeAttribute()]
[SettingsSerializeAs(SettingsSerializeAs.Binary)]
public Hashtable MyHashtable
{
get { return ((Hashtable)(this["MyHashtable"])); }
set { this["MyHashtable"] = value; }
}
}
Program.cs的
class Program
{
static void Main(string[] args)
{
// For the first time no Hastable will exist.
// Create one with the default values
if (MyCustomSettings.Default.MyHashtable == null)
{
Console.WriteLine("Initializing Hashtable...");
MyCustomSettings.Default.MyHashtable = new Hashtable();
MyCustomSettings.Default.MyHashtable.Add(1, "foo");
MyCustomSettings.Default.MyHashtable.Add(2, "bar");
MyCustomSettings.Default.Save();
}
foreach (DictionaryEntry entry in MyCustomSettings.Default.MyHashtable)
{
Console.WriteLine(entry.Key + ": " + entry.Value);
}
Console.ReadKey();
}
}
<强>更新强> 如果您想要人类可读的数据表示,那么您使用的方法似乎是合理的。尽管如此,您还可以尝试使用不同的方法来更好地封装转换为字符串(XML)和字符串(XML)的逻辑。
此方法允许您使用IDE支持Settings.settings文件,无需生成自定义设置类或使用App.config搞乱。
您只需要实现一个保存数据的自定义类,在我的示例中,我将从StringDictionary继承此类,并实现设置系统将用于以字符串格式保存数据的TypeConverter
[TypeConverter(typeof(StringDictionaryTypeConverter))]
public class MyStringDictionary : StringDictionary
{
}
public class StringDictionaryTypeConverter : TypeConverter
{
public override bool CanConvertFrom(
ITypeDescriptorContext context,
Type sourceType)
{
if (sourceType.Equals(typeof(string)))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(
ITypeDescriptorContext context,
Type destinationType)
{
if (destinationType.Equals(typeof(string)))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(
ITypeDescriptorContext context,
CultureInfo culture,
object value)
{
if (value is string)
{
MyStringDictionary sd = new MyStringDictionary();
XDocument xs = XDocument.Load(new StringReader(value as string));
foreach (var item in xs.Descendants("entry"))
{
sd.Add(item.Element("key").Value, item.Element("value").Value);
}
return sd;
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(
ITypeDescriptorContext context,
CultureInfo culture,
object value,
Type destinationType)
{
if (destinationType.Equals(typeof(string)))
{
MyStringDictionary sd = value as MyStringDictionary;
StringBuilder sb = new StringBuilder();
sb.Append("<entries>");
foreach (DictionaryEntry item in sd)
{
sb.AppendFormat(
"<entry><key>{0}</key><value>{1}</value></entry>",
item.Key,
item.Value);
}
sb.Append("</entries>");
return sb.ToString();
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
现在您只需要使用MyStringDictionary类作为设置的数据类型。由于Visual Studio不在用户设置的可用数据类型中显示用户类,因此您需要执行一次性解决方法,包括使用XML编辑器打开Settings.settings文件(右键单击并打开宽度)并手动指定用户设置的类型为MyStringDictionary的全名。
希望这有帮助。