2017年5月9日 星期二

Using TypeConverters to convert AppSettings value

App.Config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="IsDebug" value="true" />
  </appSettings>
</configuration>


C# Code
boolean debugSetting = Convert.ToBoolean(ConfigurationManager.AppSettings["IsDebug"]);
if(debugSetting){
    //do something
}




Use Type Converters
public static class AppSettings
{
    public static T Get<T>(string key)
    {
        var appSetting = ConfigurationManager.AppSettings[key];
        if (string.IsNullOrWhiteSpace(appSetting)) throw new AppSettingNotFoundException(key);
        
        var converter = TypeDescriptor.GetConverter(typeof(T));
        return (T)(converter.ConvertFromInvariantString(appSetting));
    }
}

//usage
boolean debugSetting = AppSettings.Get<bool>("Debug");



Web.Config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="IsDebug" value="true" />
    <add key="MyEnumValue" value="1" />
    <add key="MyEnumValue2" value="A" />
    <add key="ServiceEndpoint" value="http://www.example.com" />
    <add key="MyFavColor" value="Red" />
  </appSettings>
</configuration>



C# Code

var isDebug = AppSettings.Get<bool>("IsDebug");
var myEnumValue = AppSettings.Get<TestEnum>("MyEnumValue");
var myEnumValue2 = AppSettings.Get<TestEnum>("MyEnumValue2");
var myFavColor = AppSettings.Get<Color>("MyFavColor");
var serviceEndpoint = AppSettings.Get<Uri>("ServiceEndpoint");

沒有留言:

張貼留言