如何强制运行时常量为编译时间常量? [英] How to force a runtime constant to be a compile time constant?

查看:52
本文介绍了如何强制运行时常量为编译时间常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 number as a default parameter for a function. Let me just let the code talk:

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);  
}

不知道指数格式,谢谢大家

was unaware of exponential format, thanks guys

推荐答案

通常不能.就编译器而言,涉及方法调用的任何内容都不是 的编译时常量.

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.

可以进行的操作是使用科学计数法表示 double 文字:

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.

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

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);

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

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

这篇关于如何强制运行时常量为编译时间常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆