Storing generic List<CustomObject> using ApplicationSettingsBase

瘦欲@ 提交于 2019-12-05 07:16:12

Agreed with Thomas Levesque:

The following class was correctly saved/read back:

public class Foo
{
    public string Name { get; set; }

    public string MashupString { get; set; }

    public override string ToString()
    {
        return Name;
    }
}

Note: I didn't need the SerializableAttribute.

Edit: here is the xml output:

<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>

And the settings class I used:

sealed class MySettings : ApplicationSettingsBase
{
    [UserScopedSetting]
    public List<Foo> Foos
    {
        get { return (List<Foo>)this["Foos"]; }
        set { this["Foos"] = value; }
    }
}

And at last the items I inserted:

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();
Thomas Levesque

In XML serialization :

  • Fields are not serialized, only properties
  • Only public properties are serialized
  • Read-only properties are not serialized either

So there is nothing to serialize in your class...

Souli7

Same here as Craig described. My Wrapper-Class did have a no-arg constructor but, it also has a generic List<T> where T didn't got a no-arg constructor so the save() failed either.

Like this:

public class foo {
    public List<bar> barList;

    public foo() {
        this.barList = new List<bar>();
    }
}

public class bar {
    public string baz;

    public bar(string baz) {
        this.baz = baz;
    }
}

Add a no-arg constructor to every custom-class wich you will use in the settings:

public bar() {
    this.baz = "";
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!