[英]checking for null values in configuration file
哪种方法更好地检查配置值是否为null?
if(ConfigurationManager.AppSettings["configValue"]!=null)
{
var _queue = ConfigurationManager.AppSettings["configValue"]
}
还是这种方式?
var _queue=ConfigurationManager.AppSettings["configValue"] ?? null;
这些东西
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";
我使用这些扩展名。 这是缩写。 还有其他几种将值解析为其他类型的方法。
这样,我可以明确显示错误消息,这样,如果需要设置但缺少设置,它不会无提示地失败或引发模糊的异常。
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项。 我可以使用默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.