2017-09-13 217 views
2

我有一些字符串常量,我需要從多個文件訪問。由於這些常量的值可能會不時變化,因此我決定將它們放在AppSettings中而不是常量類中,以便每次更改常量時都不必重新編譯。C#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"]]; 
    //... 
} 

有沒有辦法做到這一點?我對此很新,我承認這可能是可怕的設計。

+0

什麼是foo的方法? –

+0

@AkashKC這只是一個將字符串作爲參數的方法。這個想法是,對於每個常量,我都會添加一些依賴於該常量的字典。 – Liam

+0

已發佈的回覆。請看看,讓我知道,如果這種方法適合你 –

回答

2

您不需要在AppSettings鍵中放置數組鍵,因爲您可以從代碼本身迭代AppSetting的所有鍵。所以,你的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"]; 
    //... 
} 
+0

哇!現在看起來很明顯。謝謝! – Liam