C# 为什么不保存Properties.Settings.Default?

C# 为什么不保存Properties.Settings.Default?,c#,.net,web-applications,persistence,application-settings,C#,.net,Web Applications,Persistence,Application Settings,我写这个是为了快速测试 为什么不保存我的设置?第一次运行此命令时,我有3个(旧)/3个(当前)元素。第二次我得到3(旧)/5(当前),第三次5(旧)/5(当前) 当我关闭应用程序时,设置完全消失。当我运行它时,它又是3。我没有对应用程序进行任何更改。为什么不保存我的设置 private void button2_Click(object sender, EventArgs e) { MyApp.Properties.Settings.Default.Reload(

我写这个是为了快速测试

为什么不保存我的设置?第一次运行此命令时,我有3个(旧)/3个(当前)元素。第二次我得到3(旧)/5(当前),第三次5(旧)/5(当前)

当我关闭应用程序时,设置完全消失。当我运行它时,它又是3。我没有对应用程序进行任何更改。为什么不保存我的设置

    private void button2_Click(object sender, EventArgs e)
    {
        MyApp.Properties.Settings.Default.Reload();
        var saveDataold = MyApp.Properties.Settings.Default.Context;
        var saveData = MyApp.Properties.Settings.Default.Context;
        saveData["user"] = textBox1.Text;
        saveData["pass"] = textBox2.Text;
        MyApp.Properties.Settings.Default.Save();
    }

您应该使用公开的属性,而不是将数据放在上下文中:

var saveData = MyApp.Properties.Settings.Default;
saveData.user = textBox1.Text;
saveData.pass = textBox2.Text;
上下文

提供上下文信息 提供程序可以在持久化时使用 背景

据我所知,它不用于存储实际设置值

更新:如果不想使用Visual Studio中的设置编辑器生成强类型属性,可以自己编写。VS生成的代码具有如下结构:

    [UserScopedSetting]
    [DebuggerNonUserCode]
    [DefaultSettingValue("")]
    public string SettingName
    {
        get { return ((string)(this["SettingName"])); }
        set { this["SettingName"] = value; }
    }
    var saveData = MyApp.Properties.Settings.Default;
    saveData["user"] = textBox1.Text;
    saveData["pass"] = textBox2.Text;
通过编辑Settings.Designer.cs文件,可以轻松添加更多属性

如果不想使用强类型属性,可以直接使用
this[name]
索引器。那么您的示例将如下所示:

    [UserScopedSetting]
    [DebuggerNonUserCode]
    [DefaultSettingValue("")]
    public string SettingName
    {
        get { return ((string)(this["SettingName"])); }
        set { this["SettingName"] = value; }
    }
    var saveData = MyApp.Properties.Settings.Default;
    saveData["user"] = textBox1.Text;
    saveData["pass"] = textBox2.Text;

顺便说一句,为什么你的问题有一半以上没有被接受的答案?那就是。。。不太好:(.那么我需要在IDE中创建属性吗?或者我可以在代码中以某种方式创建属性吗?糟糕的是,我不能只向您提供点数。回答很好。我研究了它,我希望我可以有一个NameValueCollection,但它看起来不可能。但是字符串版本可用。我猜对象/装箱不可用。如果我想生成字段(ATM我只是喜欢在IDE上内联和代码中编写字段)我可以使用字符串集合,这并不坏。如果你在接受之前在这个问题上增加了悬赏,你可以,哈哈!无论如何,很高兴能提供帮助。