代码分析建议在定义中使用 const,但在 global.asax 中如何使用?

发布于 2024-10-15 20:59:22 字数 582 浏览 2 评论 0原文

代码

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

迟月 2024-10-22 20:59:22

将它们声明为只读并将初始化移至构造函数:

public class Global : System.Web.HttpApplication
{

    public readonly string globalServernameSHA;
    public readonly string globalSqlConnection;

    public Global()
    {
        globalServernameSHA = ConfigurationManager.AppSettings["varServernameSHA"].ToString();
        globalSqlConnection = ConfigurationManager.ConnectionStrings["varConnectionString"].ToString();
    }

Declare them as readonly and move initialization to constructor:

public class Global : System.Web.HttpApplication
{

    public readonly string globalServernameSHA;
    public readonly string globalSqlConnection;

    public Global()
    {
        globalServernameSHA = ConfigurationManager.AppSettings["varServernameSHA"].ToString();
        globalSqlConnection = ConfigurationManager.ConnectionStrings["varConnectionString"].ToString();
    }
软糯酥胸 2024-10-22 20:59:22

它们不能声明为 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 a ref.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文