Namespace constant in C#

前端 未结 4 1360
感动是毒
感动是毒 2020-12-08 00:07

Is there any way to define a constant for an entire namespace, rather than just within a class? For example:

namespace MyNamespace
{    
    public const st         


        
相关标签:
4条回答
  • 2020-12-08 00:27

    This is not possible

    From MSDN:

    The const keyword is used to modify a declaration of a field or local variable.

    Since you can only have a field or local variable within a class, this means you cannot have a global const. (i.e namespace const)

    0 讨论(0)
  • 2020-12-08 00:32

    No, there is not. Put it in a static class or enum.

    0 讨论(0)
  • 2020-12-08 00:33

    You can use the constants in your other classes if you add the "Using Static" too:

    using static MyNameSpace.MyGlobals;
    
    namespace MyNameSpace {
        public static class MyGlobals{
            public const bool SAVE_LOGSPACE = true;
            public static readonly DateTime BACKTEST_START_DATE = new DateTime(2019,03,01);
    }
    
    0 讨论(0)
  • 2020-12-08 00:36

    I believe it's not possible. But you can create a Class with only constants.

    public static class GlobalVar
    {
        public const string MY_CONST = "Test";
    }
    

    and then use it like

    class Program
    {
        static void Main()
        {
            Console.WriteLine(GlobalVar.MY_CONST);
        }
    }
    
    0 讨论(0)
提交回复
热议问题