C# 如何使设置数组 WinForms

本文关键字:数组 WinForms 设置 何使 | 更新日期: 2023-09-27 18:33:33

我的项目设置中有大约 10 个 bool 类型的设置。我想有一个列表或数组来存储这些变量,但我也需要每当我更改一些数组/列表索引值时,设置值也应该更改。我目前将它们声明为:

private static bool[] CombinationAchievements =
    {
        Properties.Settings.Default.GetStraight,
        Properties.Settings.Default.GetFlush,
        Properties.Settings.Default.GetFullHouse,
        Properties.Settings.Default.GetFourOfAKind,
        Properties.Settings.Default.GetStraightFlush,
        Properties.Settings.Default.GetRoyalFlush
    };

但是,当我更改CombinationAchievements[0] = true时,Properties.Settings.Default.GetStraight值仍然等于 false。我可以创建一个将编辑设置的方法,但它主要是硬编码的:

private void Test(bool[] editSettings)
{
    properties.settings.default.GetStraight= editSettings[0];
    properties.settings.default.GetFlush= editSettings[1];
    .
    .
    .
}

只是一个伪代码。但是,如果我有 100 个设置,想象一下它看起来一点也不好。我所需要的只是可以容纳我所有设置的东西,因此该功能可以如下所示:

private void Test(bool[] editSettings)
{
    List<properties.settings.default> thisIsNotHowYouDoItMate = new List<properties.settings.default>
    for(int i = 0;i<thisIsNotHowYouDoItMate.count;i++)
    {
        thisIsNotHowYouDoItMate[i]=editSettings[i];
    }     
}

上面的代码是我试图实现的,当然这是废话,但我希望你明白了。

C# 如何使设置数组 WinForms

因此,如果您想使用XML文件作为存储进行自定义设置,这里有一个如何实现它的示例:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
namespace XMLConfigurationExample
{
    public sealed class Configuration
    {
        private readonly List<Setting> _settings = new List<Setting>();
        private readonly object _lock = new object();
        private readonly XmlSerializer _serializer;
        private const string FileName = "settings.xml";
        public Configuration()
        {
            _serializer = new XmlSerializer(typeof(List<Setting>));
            LoadSettings();
        }
        public object this[string key]
        {
            get
            {
                Setting setting = _settings.FirstOrDefault(s => s.Key == key);
                if (setting != null)
                {
                    return setting.Value;
                }
                return null;
            }
            set
            {
                Setting setting = _settings.FirstOrDefault(s => s.Key == key);
                if (setting != null)
                {
                    lock (_lock)
                    {
                        setting.Value = value;
                    }
                    SaveSettings();
                }
            }
        }
        private void SaveSettings()
        {
            try
            {
                using (FileStream fileStream = File.Open(FileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
                {
                    _serializer.Serialize(fileStream, _settings);
                }
            }
            catch (Exception ex)
            {
                // here your real error handling
                Debugger.Log(100, "Error", ex.Message);
                throw;
            }
        }
        private void LoadSettings()
        {
            if (!File.Exists(FileName))
            {
                return;
            }
            try
            {
                using (FileStream fileStream = File.Open(FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    ((List<Setting>)_serializer.Deserialize(fileStream)).ForEach(s => _settings.Add(s));
                }
            }
            catch (Exception ex)
            {
                // here your real error handling
                Debugger.Log(100,"Error",ex.Message);
                throw;
            }
        }
        public void AddSetting(string key)
        {
            if (_settings.All(s => s.Key != key))
            {
                _settings.Add(new Setting { Key = key });
            }
        }
        public void RemoveSetting(string key)
        {
            Setting setting = _settings.FirstOrDefault(s => s.Key == key);
            if (setting != null)
            {
                _settings.Remove(setting);
            }
        }
    }
}

设置模型:

using System.Runtime.Serialization;
namespace XMLConfigurationExample
{
    [DataContract]
    public class Setting
    {
        [DataMember]
        public string Key { get; set; }
        [DataMember]
        public object Value { get; set; }
    }
}

以及在例如控制台应用程序中的用法:

Configuration configuration = new Configuration();
configuration.AddSetting("Test");
configuration.AddSetting("Test2");
configuration["Test"] = "value1";
configuration["Test2"] = 12.040;
// here your real output or using of the configuration
Debugger.Log(100, "Log", configuration["Test"].ToString());
Debugger.Log(100, "Log", configuration["Test2"].ToString());

配置应该只在应用程序中实例化一次,例如用作读取和写入的单例。