简体   繁体   English

检查配置文件中的空值

[英]checking for null values in configuration file

Which way is better to check whether a config value is null? 哪种方法更好地检查配置值是否为null?

if(ConfigurationManager.AppSettings["configValue"]!=null)
{
  var _queue = ConfigurationManager.AppSettings["configValue"]
}

or this way? 还是这种方式?

var _queue=ConfigurationManager.AppSettings["configValue"] ?? null;

something along these lines 这些东西

string val = ConfigurationManager.AppSettings["configValue"];
if (val == null)
    Console.WriteLine("Missing appSettings configuration 'configValue'");
else if (val == string.Empty)
    Console.WriteLine("appSettings configuration 'configValue' not set");
else
    Console.WriteLine("appSettings configuration 'configValue' is " + val);

But usually, even if someone has not set value, you want your application to still function... 但是通常,即使有人没有设置值,您仍然希望您的应用程序仍然可以运行...

string val = ConfigurationManager.AppSettings["configValue"];
if (string.IsNullOrWhiteSpace(val))
    val = "default value";

I use these extensions. 我使用这些扩展名。 This is abbreviated. 这是缩写。 There are a few other methods for parsing values to other types. 还有其他几种将值解析为其他类型的方法。

This way I can be explicit with the error messages so that if a setting is required but missing it doesn't fail silently or throw a vague exception. 这样,我可以明确显示错误消息,这样,如果需要设置但缺少设置,它不会无提示地失败或引发模糊的异常。

public static class AppSettingsExtensions
{
    public static string Required(this NameValueCollection appSettings, string key)
    {
        var settingsValue = appSettings[key];
        if (string.IsNullOrEmpty(settingsValue))
            throw new MissingAppSettingException(key);
        return settingsValue;
    }

    public static string ValueOrDefault(this NameValueCollection appSettings, string key, string defaultValue)
    {
        return appSettings[key] ?? defaultValue;
    }
}

public class MissingAppSettingException : Exception
{
    internal MissingAppSettingException(string key, Type expectedType)
        : base(string.Format(@"An expected appSettings value with key ""{0}"" and type {1} is missing.", key, expectedType.FullName))
    { }
    public MissingAppSettingException(string key)
        : base(string.Format(@"An expected appSettings value with key ""{0}"" is missing.", key))
    { }
}

Usage: 用法:

    var setting = ConfigurationManager.AppSettings.Required("thisCantBeMissing");
    var optionalSetting = ConfigurationManager.AppSettings.ValueOrDefault("thisCanBeMissing", "default value");

The second one is handy because I often never need to create the appSettings key. 第二个非常方便,因为我经常不需要创建appSettings项。 I can just use the default. 我可以使用默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM