配置管理器静态类 [英] ConfigurationManager & Static Class
问题描述
我想使用 ConfigurationManager
从 static 类访问一些字符串值。但是,我需要专门处理不存在值或存在空值的情况。现在,我正在使用类型初始化器,例如
I would like to use ConfigurationManager
to access some string values from a static class. However, I need to handle specifically the absence of a value or the presence of empty values. Right now I was using type initializers, like
private static readonly string someStr = ConfigurationManager.AppSettings["abc"];
做这项工作。但是,如果 App.config
中不存在键为 abc的字符串,则执行将以 null $ c $继续进行c>引用代替
someStr
。那么,什么是在初始化时验证此值的最佳方法?我在其中初始化值然后检查有效性的静态构造函数?我听说应该避免使用静态构造函数,并在可能的情况下将其替换为类型初始值设定项。
to do the job. However, if a string with key "abc" doesn't exist in App.config
the execution will happilly continue with a null
reference in place of someStr
. What is, then, the best way to validate this value on initialization? A static constructor in which I initialize the value and then check for validity? I heard static constructors are to be avoided and replaced by type initializers when possible.
推荐答案
我使用的是这样的东西: / p>
I'm using something like this:
public static readonly string someStr =
ConfigurationManager.AppSettings["abc"] ?? "default value";
或处理空字符串:
public static readonly string someStr =
!String.IsNullOrEmpty(ConfigurationManager.AppSettings["abc"]) ?
ConfigurationManager.AppSettings["abc"] : "default value";
这篇关于配置管理器静态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!