在单独的文件中的全局常量。这是个好主意吗? [英] Global constants in separate file. Is it a good idea?

查看:137
本文介绍了在单独的文件中的全局常量。这是个好主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前工作的ASP.NET MVC应用程序。我打算创造一个我计划容纳所有的全球字符串常量像会话名称的静态类。

I'm currently working on ASP.NET MVC application. I'm planning to create a static class where I plan to hold all the global string constants like session names.

我犹豫的原因是因为它是一种味道,但我不知道更好的选择。

The reason I'm hesitant is because it's kind of smell but I'm not aware of better alternative.

请告诉我光如何定义全局常量。

Please show me the light how to define global constants.

推荐答案

瓦迪姆,

我做的完全一样,你提出并使用一个静态类用于此目的。那么你得到的强类型访问PLUS添加覆盖(以方法的形式)的能力的优势,如果您需要他们。

i do exactly as you propose and use a static class for this purpose. You then get the advantage of strongly typed accessors PLUS the ability to add overrides (in the form of methods), should you require them.

这里有一个片段:

public static class Config
{
    private const string NotSet = "**VALUE NOT SET**";
    private const int pageSize = 5;

    public static string CustomCache
    {
        get
        {
            return ConfigurationManager.AppSettings["CustomCache"] ?? NotSet;
        }
    }

    public static int PageSize
    {
        get
        {
            // simple default - no setter
            return pageSize; 
        }
    }
}

典型用法:

items = _repository.GetPaged(pageNumber, Config.PageSize)

在上面的类,某些设置被称为第二代从web.config中的应用程序设置,但在类强类型,以确保运行错误检查等人纯粹是在类中定义的静态设置。

in the above class, some settings are called '2nd generation' from the app settings in the web.config but with strong typing in the classes to ensure runtime error checking etc.. others are purely static settings defined in the class.

它的灵活度做任何的上面(在我看来)给出了这种方法既吸引力和真正的实力。

it's the flexibility to do all of the above that (in my opinion) gives this approach both appeal and a real strength.

这篇关于在单独的文件中的全局常量。这是个好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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