繁体   English   中英

C#如何使设置数组WinForms

[英]C# How to make settings array WinForms

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

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] = trueProperties.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];
    }     
}

上面的代码是我试图实现的目标,当然这是胡扯,但我希望您能明白。

因此,如果要使用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());

配置仅应在您的应用程序中实例化一次,并用作读取和写入的单例。

暂无
暂无

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

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