如何在应用程序设置中存储对象列表

Ehs*_*san 16 c# application-settings

我最近熟悉了C#应用程序设置,看起来很酷.
我正在寻找一种存储自定义对象列表的方法,但我找不到方法!
实际上我看到了一个存储int []帖子,但它对这个问题没有帮助.
我试图更改该解决方案的配置,以使其适合我的问题.它的XML配置文件是:

<Setting Name="SomeTestSetting" Type="System.Int32[]" Scope="User">
  <Value Profile="(Default)" />
</Setting>
Run Code Online (Sandbox Code Playgroud)

我尝试在type属性中引用我的对象,但它没有帮助,因为它没有识别我的对象...我尝试了"type = List"和"type ="tuple []"
这两个选项没帮我!

我有一个类看起来像:

class tuple
    {
        public tuple()
        {
            this.font = new Font ("Microsoft Sans Serif",8);
            this.backgroundcolor_color = Color.White;
            this.foregroundcolor_color = Color.Black;
        }
        public string log { get; set; }
        public Font font { get ; set; }
        public String fontName { get; set; }
        public string foregroundcolor { get; set; }
        public Color foregroundcolor_color { get; set; }
        public string backgroundcolor { get; set; }
        public Color backgroundcolor_color { get; set; }
        public Boolean notification { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

我想在应用程序设置中存储一个列表.
那么有没有办法达到这个目的.
提前致谢.
干杯,

Mic*_*aga 34

您可以使用BinaryFormatter将元组列表序列化为字节数组,并使用Base64(作为非常有效的方式)将字节数组存储为string.

首先将你的类更改为类似的东西(提示:) [SerializableAttribute]:

[Serializable()]
public class tuple
{
    public tuple()
    {
        this.font = new Font("Microsoft Sans Serif", 8);
    //....
}
Run Code Online (Sandbox Code Playgroud)

在名为的设置tuples和类型中添加属性string.

然后,您可以使用两种方法来加载和保存元组的通用列表(List<tuple>):

void SaveTuples(List<tuple> tuples)
{
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(ms, tuples);
        ms.Position = 0;
        byte[] buffer = new byte[(int)ms.Length];
        ms.Read(buffer, 0, buffer.Length);
        Properties.Settings.Default.tuples = Convert.ToBase64String(buffer);
        Properties.Settings.Default.Save();
    }
}

List<tuple> LoadTuples()
{
    using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(Properties.Settings.Default.tuples)))
    {
        BinaryFormatter bf = new BinaryFormatter();
        return (List<tuple>)bf.Deserialize(ms);
    }
}
Run Code Online (Sandbox Code Playgroud)

例:

List<tuple> list = new List<tuple>();
list.Add(new tuple());
list.Add(new tuple());
list.Add(new tuple());
list.Add(new tuple());
list.Add(new tuple());

// save list
SaveTuples(list);

// load list
list = LoadTuples();
Run Code Online (Sandbox Code Playgroud)

我离开null,空字符串和异常检查由你决定.