为什么通过构造函数向ApplicationSettingsBase中的List <t>添加自定义对象不起作用?</t>

时间:2010-05-05 17:55:31

标签: c# applicationsettingsbase

这与another 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();
}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

public Foo() { }

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