代码之家  ›  专栏  ›  技术社区  ›  Liam

C#AppSettings数组

  •  2
  • Liam  · 技术社区  · 7 年前

    我需要从多个文件中访问一些字符串常量。由于这些常数的值可能会不时更改,我决定将它们放在AppSettings中,而不是常数类中,这样我就不必每次更改常数时都重新编译。

    有时我需要处理单个字符串,有时我需要同时处理所有字符串。我想这样做:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <appSettings>
            <add key="CONST1" value="Hi, I'm the first constant." />
            <add key="CONST2" value="I'm the second." />
            <add key="CONST3" value="And I'm the third." />
    
            <add key="CONST_ARR" value=[CONST1, CONST2, CONST3] />
        </appSettings>
    </configuration>
    

    理由是这样我就可以做

    public Dictionary<string, List<double>> GetData(){
        var ret = new Dictionary<string, List<double>>();
        foreach(string key in ConfigurationManager.AppSettings["CONST_ARR"])
            ret.Add(key, foo(key));
        return ret;
    }
    
    //...
    
    Dictionary<string, List<double>> dataset = GetData();
    
    public void ProcessData1(){
        List<double> data = dataset[ConfigurationManager.AppSettings["CONST1"]];
        //...
    }
    

    有办法做到这一点吗?我对这个很陌生,我承认这可能是一个可怕的设计。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Akash KC    7 年前

    您不需要将密钥数组放入 AppSettings 应用程序设置 应该是这样的:

     <appSettings>
        <add key="CONST1" value="Hi, I'm the first constant." />
        <add key="CONST2" value="I'm the second." />
        <add key="CONST3" value="And I'm the third." />
    </appSettings>
    

    在此之后,您可以创建全局静态字典,您可以从程序的所有部分访问该字典:

    public static Dictionary<string, List<double>> Dataset
    {
           get
           {
                var ret = new Dictionary<string, List<double>>();
                // Iterate through each key of AppSettings
                foreach (string key in ConfigurationManager.AppSettings.AllKeys)
                    ret.Add(key, Foo(ConfigurationManager.AppSettings[key]));
                eturn ret;
            }
    }
    

    Foo method static 属性,则需要将Foo方法定义为静态方法。因此,您的Foo方法应该如下所示:

    private static List<double> Foo(string key)
    {
        // Process and return value 
        return Enumerable.Empty<double>().ToList(); // returning empty collection for demo
    }
    

    dictionary

    public void ProcessData1()
    {
        List<double> data = Dataset["CONST1"];
        //...
    }