0

这与另一个 SO question 密切相关。

使用下面的示例,有人可以向我解释为什么List<Foo>在显式设置 Foo 的每个属性的地方添加一个新的会导致该ApplicationSettingsBase.Save()方法正确存储数据,而通过构造函数将新的 Foo 添加到列表中(构造函数设置属性值) 不工作?谢谢!

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();
}
4

2 回答 2

0

这可能是由于您构建示例的方式。但是使用给定的代码,当您执行“有效”部分时,“无效”列表将被删除。如果您希望两个元素都theList位于方法的末尾,则只能进行一次new List<Foo>()调用。

于 2010-05-05T18:01:31.110 回答
0

我刚刚在试图澄清我的问题时偶然发现了答案。如果我为 Foo 类提供默认构造函数:

public Foo() { }

-- 保持其他所有内容相同 -- 然后在执行时类的值正确存储在 user.config 文件ApplicationSettingsBase.Save()中。奇怪的。

于 2010-05-05T19:08:19.580 回答