使用ApplicationSettingsBase保存自定义设置的C#中的自定义对象的列表 [英] Custom Settings with ApplicationSettingsBase saving List of custom objects in C#

查看:307
本文介绍了使用ApplicationSettingsBase保存自定义设置的C#中的自定义对象的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我的自定义课程:

[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始终为零.我不知道为什么我的名单不想保存.有人可以帮我吗?谢谢!

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!

推荐答案

您需要使用[SettingsSerializeAs(SettingsSerializeAs.Binary)]装饰属性:

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

应用程序设置体系结构»设置持久性»设置序列化
如果您实现自己的设置类,则可以使用 SettingsSerializeAsAttribute 到将设置标记为二进制或 使用 SettingsSerializeAs 枚举.

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.

这篇关于使用ApplicationSettingsBase保存自定义设置的C#中的自定义对象的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆