【问题标题】:Custom Settings with ApplicationSettingsBase saving List of custom objects in C#带有 ApplicationSettingsBase 的自定义设置保存 C# 中的自定义对象列表
【发布时间】:2017-03-13 02:02:01
【问题描述】:

我正在尝试将ApplicationSettingsBase 与自定义对象的保存列表一起使用。这是我的应用程序设置类:

internal class ApplicationSettings: ApplicationSettingsBase
{
    [DefaultSettingValue(""), UserScopedSetting]
    public List<MyAwesomeClass> MyObjects
    {
        get
        {
            try
            {
                return this["MyObjects"] as    List<MyAwesomeClass>;
            }
            catch (SettingsPropertyNotFoundException)
            {
                return null;
            }             
        }
    }

    public void Add(MyAwesomeClass val)
    {
        MyObjects.Add(val);
        this["MyObjects"] =  MyObjects;
    }
}

这是我的自定义类:

[Serializable]
public class MyAwesomeClass 
{
    public Guid Id { get; set; }
    public string SomeStringProperty{ get; set; }
    public bool SomeBooleanProperty{ get; set; }
}

这是用法:

_applicationSettings = new ApplicationSettings();
_applicationSettings.Add(new MyAwesomeClass {/*Some initial values*/});
_applicationSettings.Save();

但当应用程序重新启动时,_applicationSettings.MyObjects 的计数始终为零。我不知道为什么我的列表不想保存。有人可以帮我吗?谢谢!

【问题讨论】:

    标签: c# .net xml winforms settings


    【解决方案1】:

    你需要用[SettingsSerializeAs(SettingsSerializeAs.Binary)]来装饰属性:

    [DefaultSettingValue(""), UserScopedSetting]
    [SettingsSerializeAs(SettingsSerializeAs.Binary)]
    public List<MyAwesomeClass> MyObjects
    

    Application Settings Architecture » 设置持久性 » 设置序列化
    如果您实现自己的设置类,则可以使用 SettingsSerializeAsAttribute 将设置标记为二进制或 使用SettingsSerializeAs 枚举进行自定义序列化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-23
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多