我有一些我想确保始终存在的 web.config 设置。我想要一种简洁的方法来执行此操作,例如为每个设置创建一个字段,并且在字段初始值设定项中,如果值为空,我会以某种方式抛出异常。
我最初的想法是使用三元运算符 ?: 但这将涉及将相同的 key 写入两次。我不想重复键名,因为这会使代码更脆弱(如果我想重命名一个键,我需要在 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();
...
}
请您参考如下方法:
这可能有点奇怪,但只要跳出框框思考,您可以向类中添加一些方法(或作为静态方法),例如:
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");
}
}
