How to force a runtime constant to be a compile time constant?

前端 未结 4 774
执笔经年
执笔经年 2021-01-18 06:30

So I am working on a chemistry based project and ran into this tricky problem. I have a bunch of functions doing chemistry type calculations and want to pass avogadros numbe

相关标签:
4条回答
  • 2021-01-18 06:40

    You can do it in exponential format: 6.022E-22

    0 讨论(0)
  • 2021-01-18 06:52

    You can't, in general. Anything which involves a method call is not going to be a compile-time constant, as far as the compiler is concerned.

    What you can do is express a double literal using scientific notation though:

    public const double AvogadrosNumber = 6.022e-22;
    

    So in this specific case you can write it with no loss of readability.

    In other settings, so long as the type is one of the primitive types or decimal, you can just write out the constant as a literal, and use a comment to explain how you got it. For example:

    // Math.Sqrt(Math.PI)
    public const double SquareRootOfPi = 1.7724538509055159;
    

    Note that even though method calls can't be used in constant expressions, other operators can. For example:

    // This is fine
    public const double PiSquared = Math.PI * Math.PI;
    
    // This is invalid
    public const double PiSquared = Math.Pow(Math.PI, 2);
    

    See section 7.19 of the C# 5 specification for more details about what is allowed within a constant expression.

    0 讨论(0)
  • 2021-01-18 06:55

    For a compile-time constant, you need to use the const keyword. But, to use it, your expression itself needs to be a compile-time constant too, as you noticed: you cannot use functions such as Math.Pow.

    class Constants
    {
        public const double avogadrosNum = 6.022E-22;
    }
    

    If you cannot or do not want to rework your constant to a compile-time constant, you cannot use it in compile-time contexts, but you could work around that by overloading, so that a runtime value can be used as sort of a default argument:

    class chemCalculations
    {
        public double genericCalc() {
            return genericCalc(Constants.avogadrosNum);
        }
        public double genericCalc(double avogadrosNum) {
            // real code here
        }
    }
    

    (By the way, the value of the constant is either wrong, or has a highly misleading name. It should most likely be 6.022E+23.)

    0 讨论(0)
  • 2021-01-18 07:02

    Just define avogadros number as scientific notation:

    class Constants 
    {
        public double const avogadrosNum = 6.022e-22;
    } 
    
    0 讨论(0)
提交回复
热议问题