检查配置文件中的空值

时间:2016-03-17 20:05:27

标签: c# .net

哪种方法最好检查配置值是否为空?

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

还是这样?

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

2 个答案:

答案 0 :(得分:1)

沿着这些方向的东西

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);

但通常情况下,即使有人没有设定价值,您也希望自己的应用程序能够正常运作......

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

答案 1 :(得分:1)

我使用这些扩展程序。这是缩写。还有一些其他方法可以将值解析为其他类型。

通过这种方式,我可以明确地显示错误消息,这样如果需要设置但缺少设置,则不会无声地失败或抛出模糊的异常。

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))
    { }
}

用法:

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

第二个很方便,因为我经常不需要创建appSettings键。我可以使用默认值。