如何强制运行时常量为编译时常量?

所以我正在研究一个基于化学的项目,并遇到了这个棘手的问题。 我有一堆函数进行化学类型计算,并希望将avogadros数作为函数的默认参数传递。 让我让代码说话:

class Constants { //must be readonly to b/c Math.Pow is calculated at run-time public static double readonly avogadrosNum = 6.022*Math.Pow(10,-22); } class chemCalculations { //getting default parameter must be a compile-time constant public double genericCalc(double avogadrosNum = Constants.avogadrosNum); } 

编辑:没有意识到指数格式,谢谢你们

一般来说,你不能。 就编译器而言,任何涉及方法调用的东西都不会是编译时常量。

可以做的是使用科学记数法表达double文字:

 public const double AvogadrosNumber = 6.022e-22; 

因此,在这种特定情况下,您可以编写它而不会损失可读性。

在其他设置中,只要类型是基本类型之一或decimal ,您就可以将常量写为文字,并使用注释来解释如何获得它。 例如:

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

请注意,即使方法调用不能在常量表达式中使用,其他运算符也可以。 例如:

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

有关常量表达式中允许的内容的更多详细信息,请参阅C#5规范的第7.19节。

对于编译时常量,您需要使用const关键字。 但是,要使用它,你的表达式本身也需要是一个编译时常量,正如你所注意到的:你不能使用Math.Pow函数。

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

如果您不能或不想将常量修改为编译时常量,则不能在编译时上下文中使用它,但是您可以通过重载来解决这个问题,以便可以将运行时值用作默认值参数:

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

(顺便说一句,常量的值要么是错误的,要么具有高度误导性的名称。它最有可能是6.022E+23

只需将avogadros数字定义为科学记数法:

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

您可以采用指数格式: 6.022E-22