如何从其他类可以使用的外部设置文件创建字典?

Ada*_*way 5 c# settings dictionary

我想从格式化为字符串列表“somekey = somevalue”的设置文件中创建一个字典。然后,我希望这个由一个类生成的键和值字典可用于我程序中的其他类,因此每次我想使用另一个类中的设置时,我都不必参考外部文件。

我已经弄清楚了第一部分,创建了一个可以读取外部文件并将字符串列表转换为字典的类,但是我不知道如何使文件读取类创建的字典数据可用于同一命名空间中的其他类。

Eri*_*itz 1

一种稍微不同的方法是使用扩展方法,我的示例相当基本,但它工作得很好

using System.Collections.Generic;

namespace SettingsDict
{
    class Program
    {
        static void Main(string[] args)
        {
            // call the extension method by adding .Settings();
            //Dictionary<string, string> settings = new Dictionary<string, string>().Settings();

            // Or by using the property in the Constants class
            var mySettings = Constants.settings;
        }
    }

    public class Constants
    {
        public static Dictionary<string, string> settings
        {
            get
            {
                return new Dictionary<string, string>().Settings();
            }
        }
    }


    public static class Extensions
    {
        public static Dictionary<string, string> Settings(this Dictionary<string, string> myDict)
        {
            // Read and split
            string[] settings = System.IO.File.ReadAllLines(@"settings.txt");

            foreach (string line in settings)
            {
                // split on =
                var split = line.Split(new[] { '=' });

                // Break if incorrect lenght
                if (split.Length != 2)
                    continue;

                // add the values to the dictionary
                myDict.Add(split[0].Trim(), split[1].Trim());
            }
            return myDict;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

设置.txt的内容

setting1=1234567890
setting2=hello
setting3=world
Run Code Online (Sandbox Code Playgroud)

结果

结果

当然,您应该使用自己的保护功能和类似功能来扩展此功能。这是一种替代方法,但使用扩展方法并没有那么糟糕。Extensions 类中的功能也可以直接在 Constants 类中的属性方法中实现。我这样做是为了好玩:)