【问题标题】:how to create a dictionary from an external settings file that can be used by other classes?如何从其他类可以使用的外部设置文件创建字典?
【发布时间】:2012-07-21 13:51:02
【问题描述】:

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

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

【问题讨论】:

  • 能否请您发布您的设置文件和代码的摘录。
  • 我不太确定你在这里得到了什么。您不能简单地将字典设为公共财产吗?

标签: c# dictionary settings


【解决方案1】:

只需将约束字典的类设为 public 和该类中的字典静态,所以

public class MyClass
{
    // ...
    public static Dictionary<string, string> checkSumKeys { get; set; }
    // ...
}

这样称呼

// ... 
foreach (KeyValuePair<string, string> checkDict in MyClass.checkSumKeys)
    // Do stuff...

或者,如果字典不是静态的,你将不得不实例化类

public class MyClass
{
    // ...
    public Dictionary<string, string> checkSumKeys { get; set; }
    // ...
}

这样称呼

MyClass myclass = new MyClass();
foreach (KeyValuePair<string, string> checkDict in myClass.checkSumKeys)
    // Do stuff...

我希望这会有所帮助。

【讨论】:

  • 我宁愿在构造函数中实现 foreach 循环。
【解决方案2】:

我不太确定你在这里得到什么。你不能简单地让字典成为那个类的公共财产吗?

好的,一种选择是使用公共属性,然后在初始化应用程序时创建该类的一个实例(如果您将其填充到类构造函数中,这将填充您的字典),然后您可以将同一个实例传递给函数或类构造函数,无需再次读取外部文件。

public class ReadFileClass
{
    //Can be replaced with auto property
    public Dictionary<string, string> Settings
    {
        Get{return Settings}
        Set{Settings = value}
    }

    public ReadFileClass()
    {
        //In this constructor you run the code to populate the dictionary
        ReadFile();
    }

    //Method to populate dictionary
    private void ReadFile()
    {
         //Do Something
         //Settings = result of doing something
    }
}

//First class to run in your application
public class UseFile
{
    private ReadFileClass readFile;

    public UseFile()
    {
        //This instance can now be used elsewhere and passed around
        readFile = new ReadFileClass();
    }

    private void DoSomething()
    {
        //function that takes a readfileclass as a parameter can use without making a new instance internally
        otherfunction(readFileClass);
    }
}

通过执行上述操作,您可以只使用对象的一个​​实例来填充设置字典,然后简单地传递它。我已经多次使用这种方法来避免对数据库或文件进行多次往返,这可能会产生代价高昂的性能影响。如果您想在另一个文件中使用包含设置的类,而不是实例化它的文件,您只需让类构造函数将其作为参数。

【讨论】:

    【解决方案3】:

    稍微不同的方法是使用扩展方法,我的示例相当基本,但效果很好

    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;
            }
        }
    }
    

    settings.txt 的内容

    setting1=1234567890
    setting2=hello
    setting3=world
    

    结果

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

    【讨论】:

      猜你喜欢
      • 2013-07-13
      • 2018-03-27
      • 1970-01-01
      • 2020-07-14
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      • 2020-09-18
      • 2019-01-06
      相关资源
      最近更新 更多