我有一些我想要确保始终存在的web.config设置。我想要一个巧妙的方法,例如为每个设置创建一个字段,在字段初始化程序中,如果值为null,我会以某种方式抛出异常。
我最初的想法是使用三元运算符?:
,但这将涉及两次写入相同的密钥。我不想重复键名,因为这会使代码变得更脆弱(我是否应该重命名一个我需要在2个位置执行的键)。有没有办法可以避免这种重复?
public class MyClass
{
//what I don't really want (won't compile):
private readonly string _name1 = ConfigurationManager.AppSettings["MyName"] != null
? ConfigurationManager.AppSettings["MyName"]
: throw new Exception();
//what I sort of want (won't compile):
private readonly string _name2 = ConfigurationManager.AppSettings["MyName"]
?? throw new Exception();
...
}
答案 0 :(得分:3)
这可能有点奇怪,但只是想在框外思考你可以为你的类添加一些方法(或作为静态方法),如:
public string ThrowConfigException(string message)
{
throw new System.Configuration.ConfigurationErrorsException(message);
}
然后,您可以向类中添加如下所示的属性:
private string _name1;
public string Name1
{
get
{
return _name1 ?? (_name1 = ConfigurationManager.AppSettings["Name1"]) ?? ThrowConfigException("Name1 does not exist in the config file");
}
}
在C#7.0中更新:您可以throw an exception inline。上面的例子现在可以写成:
private string _name1;
public string Name1
{
get
{
return
_name1 ??
(_name1 = ConfigurationManager.AppSettings["Name1"]) ??
throw new System.Configuration.ConfigurationErrorsException(nameof(Name1) + " does not exist in the config file");
}
}
答案 1 :(得分:2)
您可以通过将逻辑分离为单独的(静态)方法,并为要测试的每个键调用它来减少大量重复代码。
public class MyClass
{
private readonly string _name1 = GetConfigValue("MyName");
private readonly string _name2 = GetConfigValue("AnotherSetting");
private static string GetConfigValue(string settingName)
{
var setting = ConfigurationManager.AppSettings[settingName];
if (setting == null)
throw new Exception(string.Format("The setting {0} is missing.", settingName));
return setting;
}
}
答案 2 :(得分:1)
您可以使用getter创建一个表示AppSettings和属性的类型,它只会读取每个值一次。
public static class Settings
{
private static string _myName;
public static string MyName
{
get
{
if (_myName == null)
{
_myName = ConfigurationManager.AppSettings["MyName"];
}
if (_myName == null)
{
throw new Exception("AppSetting 'MyName' is not present in the application configuration file.");
}
return _myName;
}
}
}