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

2024-01-07

最近熟悉了C#应用程序设置,看起来很酷。
我正在寻找一种存储自定义对象列表的方法,但我找不到方法!
其实我看到了一个发布到存储 int[] https://stackoverflow.com/questions/1766610/how-to-store-int-array-in-application-settings,但这对这个问题没有帮助。
我尝试更改该解决方案的配置,以使其适合我的问题。 XML 配置文件是:

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

我尝试按照下面在 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; }
    }

我想在应用程序设置中存储一个列表。
那么有没有什么办法可以达到这个目的呢。
提前致谢。
Cheers,


您可以使用二进制格式化程序 http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter.aspx将元组列表序列化为字节数组和 Base64(作为非常有效的方式)将字节数组存储为string.

首先,将您的课程更改为类似的内容(提示:[SerializableAttribute] http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx):

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

在名为的设置中添加属性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);
    }
}

Example:

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();

I leave null、空字符串和异常检查由您决定。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在应用程序设置中存储对象列表 的相关文章

随机推荐