我正在尝试保存列表< Foo>使用ApplicationSettingsBase,但即使填充了列表,它也只输出以下内容:
- <setting name="Foobar" serializeAs="Xml">
- <value />
- </setting>
Foo定义如下:
- [Serializable()]
- public class Foo
- {
- public String Name;
- public Keys Key1;
- public Keys Key2;
- public String MashupString
- {
- get
- {
- return Key1 + " " + Key2;
- }
- }
- public override string ToString()
- {
- return Name;
- }
- }
如何启用ApplicationSettingsBase来存储List< Foo>?
解决方法
同意Thomas Levesque:
以下类已正确保存/读回:
- public class Foo
- {
- public string Name { get; set; }
- public string MashupString { get; set; }
- public override string ToString()
- {
- return Name;
- }
- }
注意:我不需要SerializableAttribute.
编辑:这是xml输出:
- <WindowsFormsApplication1.MySettings>
- <setting name="Foos" serializeAs="Xml">
- <value>
- <ArrayOfFoo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:xsd="http://www.w3.org/2001/XMLSchema">
- <Foo>
- <Name>Hello</Name>
- <MashupString>World</MashupString>
- </Foo>
- <Foo>
- <Name>Bonjour</Name>
- <MashupString>Monde</MashupString>
- </Foo>
- </ArrayOfFoo>
- </value>
- </setting>
- </WindowsFormsApplication1.MySettings>
我使用的设置类:
- sealed class MySettings : ApplicationSettingsBase
- {
- [UserScopedSetting]
- public List<Foo> Foos
- {
- get { return (List<Foo>)this["Foos"]; }
- set { this["Foos"] = value; }
- }
- }
最后我插入的项目:
- private MySettings fooSettings = new MySettings();
- var list = new List<Foo>()
- {
- new Foo() { Name = "Hello",MashupString = "World" },new Foo() { Name = "Bonjour",MashupString = "Monde" }
- };
- fooSettings.Foos = list;
- fooSettings.Save();
- fooSettings.Reload();