Custom Settings with ApplicationSettingsBase saving List of custom objects in C#

拈花ヽ惹草 提交于 2019-12-24 06:50:47

问题


I am trying to use ApplicationSettingsBase with saving list of custom objects. Here is my application settings class:

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;
    }
}

Here is my custom class:

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

And here is the usage:

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

But when application restarts _applicationSettings.MyObjects is always have zero count. I don't know why my list doesn't want saving. Can anybody help me with this? Thanks!


回答1:


You need to decorate the property with [SettingsSerializeAs(SettingsSerializeAs.Binary)]:

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

Application Settings Architecture » Setting Persistence » Settings Serialization
If you implement your own settings class, you can use the SettingsSerializeAsAttribute to mark a setting for either binary or custom serialization using the SettingsSerializeAs enumeration.



来源:https://stackoverflow.com/questions/40334532/custom-settings-with-applicationsettingsbase-saving-list-of-custom-objects-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!