Difference between static and const variables [dup

2020-03-12 03:23发布

问题:

what is the difference between "static" and "const" when it comes to declare global variables;

namespace General
{
    public static class Globals
    {
        public const double GMinimum = 1e-1;

        public const double GMaximum = 1e+1;
    }
}

which one is better (considering that these variables wont be changing ever)

namespace General
{
    public static class Globals
    {
        public static double GMinimum1 = 1e-1;

        public static double GMaximum1 = 1e+1;
    }
}

回答1:

const and readonly perform a similar function on data members, but they have a few important differences. A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the const keyword and must be initialized as they are declared.

The static modifier is used to declare a static member, this means that the member is no longer tied to a specific object. The value belongs to the class, additionally the member can be accessed without creating an instance of the class. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events



回答2:

const variables cannot be changed ever after compile time. They are good for things that are truly constant (i.e. pi)

static members are shared memory that is accessible by all instances of a particular class and more if access modifiers like public are used (these may feel like globals variables in languages like javascript). Static members behave like normal variables that can be reassigned whenever.

In your case if the numbers are guaranteed never to change then make them const. If they do change you would have to recompile the program with a new value.


Which one is better? if you use const then the literal values get baked into the assembly and provide a performance boost.

If the values ever need to change then the time taken to change the source and recompile quickly ruins this marginal performance increase.



回答3:

const is a constant value, and cannot be changed. It is compiled into the assembly.

static means that it is a value not related to an instance, and it can be changed at run-time (since it isn't readonly).

So if the values are never changed, use consts.