【问题标题】:C# How to make settings array WinFormsC#如何使设置数组WinForms
【发布时间】:2016-05-16 13:59:51
【问题描述】:

我的项目设置中有大约 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];
    }     
}

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

【问题讨论】:

  • 只要你必须调用 100 个属性设置器,它就永远不会漂亮。 System.Configuration 是微弱的,NameValueCollection 几乎和它一样好。通过声明一个枚举使其变得更好。
  • 那么现在有办法将它们存储在数组中吗?同样使用枚举,每次我正确时我都必须强制转换 (int) :?
  • 也许您最好使用自己的配置,使用 xml 序列化文件?
  • 在我的情况下 xml 序列化如何提供帮助:?

标签: c# arrays winforms resources boolean


【解决方案1】:

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

配置应该在您的应用程序中仅实例化一次并使用,例如作为读写的单身人士。

【讨论】:

  • 这是win表格,您可以使用console.writeline等编辑部分吗?
  • 请查看我的更改。当然,您需要根据实际的 winform 应用程序调整实现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多