开发者

Why adding custom objects to List<T> in ApplicationSettingsBase via constructor doesn't work?

This is pretty closely related to another SO question.

Using the example below, could someone explain to me why adding a new List<Foo> where each of Foo's properties are explicitly set causes the ApplicationSettingsBase.Save() method to correctly store the data, whereas adding a new Foo to the list via a constructor (where the constructor sets the property values) does not work? Thanks!

public class Foo
{
    public Foo(string blah, string doh)
    {
        this.Blah = blah;
        this.Doh = doh;
    }

    public Foo() { }

    public string Blah { get; set; }
    public string Doh { get; set; }
}

public sealed class MySettings : ApplicationSettingsBase
{
    [UserScopedSetting]
    public List<Foo> MyFoos
    {
        get { 开发者_如何学编程return (List<Foo>)this["MyFoos"]; }
        set { this["MyFoos"] = value; }
    }
}

// Here's the question...
private void button1_Click(object sender, EventArgs e)
{
    MySettings mySettings = new MySettings();

    // Adding new Foo's to the list using this block of code doesn't work.
    List<Foo> theList = new List<Foo>()
    { 
        new Foo("doesn't","work")
    };

    // But using this block of code DOES work.
    List<Foo> theList = new List<Foo>()
    { 
        new Foo() {Blah = "DOES", Doh = "work"}
    };

   // NOTE: I never ran both the above code blocks simultaneously. I commented
   // one or the other out each time I ran the code so that `theList` was 
   // only created once.

    mySettings.MyFoos = theList;
    mySettings.Save();
}


This might be due to how you constructed your example. But using the given code, the "doesn't work" list is getting removed when you do the "does work" section. If you want both elements to be in theList at the end of the method, you can only have one new List<Foo>() call.


I stumbled upon the answer while trying to clarify my question just now. If I supply a default constructor to the Foo class:

public Foo() { }

--leaving everything else the same--then the values of the class are correctly stored in the user.config file when ApplicationSettingsBase.Save() is executed. Weird.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜