代码分析建议在定义中使用 const,但在 global.asax 中如何使用?
代码
public class Global : System.Web.HttpApplication
{
public const string globalServernameSHA = string.Empty;
public static string globalSqlConnection = string.Empty;
protected void Application_Start(object sender, EventArgs e)
{
globalServernameSHA = ConfigurationManager.AppSettings["varServernameSHA"].ToString();
globalSqlConnection = ConfigurationManager.ConnectionStrings["varConnectionString"].ToString();
}
这些变量应该只读取一次,并且绝对应该是只读的。 它们必须可用于整个项目,因此应该是公开的。
有没有办法在这样的代码中定义 const ?
谢谢
Code
public class Global : System.Web.HttpApplication
{
public const string globalServernameSHA = string.Empty;
public static string globalSqlConnection = string.Empty;
protected void Application_Start(object sender, EventArgs e)
{
globalServernameSHA = ConfigurationManager.AppSettings["varServernameSHA"].ToString();
globalSqlConnection = ConfigurationManager.ConnectionStrings["varConnectionString"].ToString();
}
These variables should be read just once and definitely should be read only.
They have to be available for whole project and therefore should be public.
Is there a way how to define const in code like this ?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将它们声明为只读并将初始化移至构造函数:
Declare them as readonly and move initialization to constructor:
它们不能声明为 const,因为该值是从设置文件中检索的。
const
值始终硬编码到可执行程序本身中。在这种情况下,readonly 是最好的选择,这意味着变量只能在构造函数中设置(实例或静态构造函数,具体取决于您定义变量的方式),或者在由当变量作为
ref
传递时的构造函数。They cannot be declared as
const
since the value is retrieved from the settings file.const
values are always hard-coded into the executable program itself.readonly
is your best bet in the circumstance, which means the variables can only be set in the constructor (the instance or static constructor, depending on how you define the variables), or in a method called by the constructor when the variable is passed as aref
.