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

前端 未结 4 825
执笔经年
执笔经年 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: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.)

提交回复
热议问题