首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么通过构造函数在List<T>中向ApplicationSettingsBase中添加自定义对象不起作用?

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

Stack Overflow用户
提问于 2010-05-05 17:55:30
回答 2查看 596关注 0票数 0

这与another SO question.密切相关。

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

代码语言:javascript
复制
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; }
    }
}

代码语言:javascript
复制
// 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();
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-05-05 19:08:19

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

代码语言:javascript
复制
public Foo() { }

--其他一切保持不变--然后在执行user.config文件时,类的值将正确地存储在ApplicationSettingsBase.Save()文件中。真奇怪。

票数 0
EN

Stack Overflow用户

发布于 2010-05-05 18:01:31

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2775574

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档