这与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();
}发布于 2010-05-05 19:08:19
我刚才在试图澄清我的问题时偶然发现了答案。如果我向Foo类提供默认构造函数:
public Foo() { }--其他一切保持不变--然后在执行user.config文件时,类的值将正确地存储在ApplicationSettingsBase.Save()文件中。真奇怪。
发布于 2010-05-05 18:01:31
这可能是由于您如何构建您的示例。但是,使用给定的代码,“不工作”列表在执行“确实工作”部分时将被删除。如果希望两个元素都在方法末尾的theList中,则只能有一个new List<Foo>()调用。
https://stackoverflow.com/questions/2775574
复制相似问题