Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#AppSettings数组_C#_.net_Configurationmanager_Appsettings - Fatal编程技术网

C#AppSettings数组

C#AppSettings数组,c#,.net,configurationmanager,appsettings,C#,.net,Configurationmanager,Appsettings,我需要从多个文件访问一些字符串常量。由于这些常量的值可能会不时更改,因此我决定将它们放入AppSettings而不是constants类中,这样我就不必每次更改常量时都重新编译 有时我需要处理单个字符串,有时我需要同时处理所有字符串。我想这样做: <?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="CONST1" value=

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

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

<?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"]];
    //...
}
公共字典GetData(){ var ret=新字典(); foreach(ConfigurationManager.AppSettings[“CONST_ARR”]中的字符串键) ret.Add(键,foo(键)); 返回ret; } //... 字典数据集=GetData(); public void ProcessData1(){ 列表数据=数据集[ConfigurationManager.AppSettings[“CONST1”]; //... }
有办法做到这一点吗?我对此非常陌生,我承认这可能是一个可怕的设计。

您不需要将密钥数组放入
AppSettings
key,因为您可以从代码本身迭代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>
private static List<double> Foo(string key)
{
    // Process and return value 
    return Enumerable.Empty<double>().ToList(); // returning empty collection for demo
}
现在,您可以通过其键以以下方式访问Dataset
dictionary

public void ProcessData1()
{
    List<double> data = Dataset["CONST1"];
    //...
}
public void ProcessData1()
{
列表数据=数据集[“常量1”];
//...
}

什么是foo方法?@AkashKC它只是一个以字符串作为参数的方法。我的想法是,对于每个常量,我都会在字典中添加一些依赖于该常量的内容。请看一看,让我知道这个方法是否适合你哇!现在看来很明显。非常感谢。
public void ProcessData1()
{
    List<double> data = Dataset["CONST1"];
    //...
}