编程语言
首页 > 编程语言> > C#-基于app.config值的不同app.config appSettings

C#-基于app.config值的不同app.config appSettings

作者:互联网

我有app.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>       
        <!--One set of properties-->
        <add key="Condition" value="A"/>
        <add key="DependingPropertyA" value="B"/>
        <add key="DependingPropertyB" value="C"/>
        <!--Another set of properties-->
        <add key="Condition" value="B"/>
        <add key="DependingPropertyA" value="D"/>
        <add key="DependingPropertyB" value="E"/>
    </appSettings>
</configuration>

所以我想如果Condition == A定义一组属性,如果Condition == B定义一组属性,那么当我在A和B之间切换时,我不需要更改所有其他属性.
可能吗?

解决方法:

如果每个“条件”的属性名称都相同(也许是环境?),那么您可以使用一些编码向导来做到这一点:

(App.Config :)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>       

    <!--Condition 'selector', change value to 'CondB' when you want to switch-->
    <add key="Condition" value="CondA"/>

    <add key="CondA.DependingPropertyA" value="B"/>
    <add key="CondA.DependingPropertyB" value="C"/>
    <add key="CondB.DependingPropertyA" value="D"/>
    <add key="CondB.DependingPropertyB" value="E"/>
  </appSettings>
</configuration>

然后,在您的C#.NET代码中说:

string keyPrepend = System.Configuration.ConfigurationManager.AppSettings["Condition"];

string propAValue = System.Configuration.ConfigurationManager.AppSettings[String.Format("{0}.{1}", keyPrepend, "DependingPropertyA")];
string propBValue = System.Configuration.ConfigurationManager.AppSettings[String.Format("{0}.{1}", keyPrepend, "DependingPropertyB")];

这使您可以根据单个条件键的值切换要使用的键/值集.

标签:configuration,app-config,config,c,net
来源: https://codeday.me/bug/20191120/2044756.html