Visual C#自定义类类型设置不会保存

时间:2016-05-02 00:40:34

标签: c# .net visual-studio collections

我有一个自定义类及其集合,我想用它来创建Settings.default中的条目。我设法使用命名空间中的browse(...)按钮在设计器中设置类型,并且在给定的会话中,它可以工作。我可以存储和获取我的类(或者更确切地说,这些类的对象)的值。

但设置无法保存。 我已经使用this method在我的设置中实现了我的自定义类,并且我尝试使用this one这样的提示来保存它们 - 但这里没有运气。

我如何保存自定义对象类? 最终类中的类型是微不足道的,只有字符串,整数和布尔值。

更新 它不是集合序列化问题,包含单个字符串的简单类也不会持续存在。我将代码更改为更简单的示例。

using System;
using System.Windows.Forms;
using System.Configuration;

namespace tester
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if(Properties.Settings.Default.MySetting== null)
            {
                MessageBox.Show("MySetting is null");
                Properties.Settings.Default.MySetting = new saveme();  // this saveme will be accessible just fine for the duration of the session, but it won't persist.
            }
            textBox1.Text = Properties.Settings.Default.MySetting.somestring;  // will always be "initial value" as per initialization of saveme()
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.MySetting.somestring = textBox1.Text;
            Properties.Settings.Default.Save();
        }
    }

    [Serializable()]
    public class saveme : ApplicationSettingsBase  // class containing data
    {
        private string Somestring = "initial value";

        [UserScopedSetting()]
        [DefaultSettingValue("default value")]
        [SettingsSerializeAs(SettingsSerializeAs.Binary)]
        public string somestring
        {
            get { return Somestring; }
            set { Somestring = value; }
        }
    }
}

MySetting始终以 null

结束

1 个答案:

答案 0 :(得分:2)

我能够重现非持久性问题,并且能够使事情发挥作用。

如果您想通过代码创建新设置,这是一个简单的工作示例。

applications/

我没有在项目属性设置标签上添加新设置。 我也避免使用Properties.Settings.Default。

我发现Properties.Settings.Default不会持久存在,并且通过测试它只对添加到项目属性设置选项卡的设置有效(持久)。

如果你想尝试它,你应该使用MyNameSpace.Properties.Settings.Default而不是普通的Properties.Settings.Default。它有所作为。