简体   繁体   English

将对象列表序列化为.settings

[英]Serializing list of objects to .settings

I was trying to serialize a list of objects to my user.settings file. 我试图将对象列表序列化到我的user.settings文件中。 I've tried a lot of things, and the only thing I got to work was the solution here. 我尝试了很多东西,我唯一能做的就是这里的解决方案。 Add a collection of a custom class to Settings.Settings I tried many different things, but this one was the only one that consistently worked. 添加一个自定义类的集合到Settings.Settings我尝试了很多不同的东西,但这是唯一一个一贯工作的东西。

Edit : What I am trying to serialize is either a List of objects (of a serializable class), or just a list of Tuples 编辑 :我想要序列化的是一个对象列表(可序列化的类),或只是一个元组列表

The solution looks like this: 解决方案如下所示:

public class Favorites: ApplicationSettingsBase
{
    [UserScopedSetting()]
    [SettingsSerializeAs(System.Configuration.SettingsSerializeAs.Binary)]
    [DefaultSettingValue("")]
    public System.Collections.ArrayList FavoritesList
    {
        get
        {
            return ((System.Collections.ArrayList)this["FavoritesList"]);
        }
        set
        {
            this["FavoritesList"] = (System.Collections.ArrayList)value;
        }
    }
}

Technically, it works. 从技术上讲,它有效。 However, I wanted to get it to work as XML serialization, not as binary. 但是,我想让它作为XML序列化工作,而不是二进制。 Switching over to SettingsSerializeAs.Xml, it doesn't serialize the settings, all I get are an empty tag for these settings. 切换到SettingsSerializeAs.Xml,它不会序列化设置,我得到的只是这些设置的空标记。 Do I have to do it differently when I serialize settings as XML? 当我将设置序列化为XML时,是否必须以不同方式执行此操作?

You can use XmlSerializer and in code serialize your collection. 您可以使用XmlSerializer并在代码中序列化您的集合。

Then you can save serialized data string into settings. 然后,您可以将序列化数据字符串保存到设置中。

Try this please, 试试这个,

public class Favorites: ApplicationSettingsBase
{
    private String[] favoritesList;

    [UserScopedSetting()]
    [System.Xml.Serialization.XmlElementAttribute("FavoritesList")]
    [DefaultSettingValue("")]
    public String[] FavoritesList
    {
        get
        {
            return (this.favoritesList);
        }
        set
        {
            this.favoritesList = value;
        }
    }
}

NOTE: I've used array of string data type. 注意:我使用了字符串数据类型的数组。 But ideally it can be an array of your custom object 但理想情况下,它可以是您的自定义对象的数组

I got it to work looking like this, with the Settings storing an object of the type "Favorites": 我看起来像这样工作,设置存储“收藏夹”类型的对象:

public sealed class Favorites : ApplicationSettingsBase
{
    public Favorites()
    {
        this.FavoritesList = new List<Favorite>();
    }

    [UserScopedSetting]
    public List<Favorite> FavoritesList
    {
        get
        {
            return (List<Favorite>)this["FavoritesList"];
        }
        set
        {
            this["FavoritesList"] = value;
        }
    }
}

[Serializable]
public class Favorit
{
    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM