配置管理器静态类 [英] ConfigurationManager & Static Class

查看:76
本文介绍了配置管理器静态类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 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 引用代替 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆