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

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

提交回复
热议问题