[英]How to do exponentiation in constant expression?
Having used the exponent operator ^
in the initialisation of a VB class's public constant following this question .在此问题之后在 VB 类的公共常量的初始化中使用了指数运算符
^
。
Public Const MaxValue As Double = MaxMantissa * (2 ^ MaxExponent)
I am converting the class to C#.我正在将类转换为 C#。 however I find that C# does not have the same operator (
^
is still an operator but only as bitwise xor).但是我发现 C# 没有相同的运算符(
^
仍然是一个运算符,但仅作为按位异或)。
Math.Pow()
is given as an alternative to the operator, but cannot be used in a constant expression. Math.Pow()
作为运算符的替代方案给出,但不能用于常量表达式。 How then can one initialise a constant with an exponent expression in C#?那么如何在 C# 中用指数表达式初始化一个常量呢?
(I do not use a value instead of an expression because the values within the expression, also constant, come from different places. MaxExponent
comes from the base class, MaxMantissa
is different in each derived class. Furthermore there are multiple constants like this in each derived class such as MaxPositiveValue
, MinPositiveValue
, MinNegativeValue
, MaxNegativeValue
, etc.) (我不使用值而不是表达式,因为表达式中的值,也是常量,来自不同的地方
MaxExponent
来自基类, MaxMantissa
在每个派生类中都不同。此外,每个类中有多个这样的常量派生类,例如MaxPositiveValue
、 MinPositiveValue
、 MinNegativeValue
、 MaxNegativeValue
等)
Since in your particular case you want to raise 2 into MaxExponent
power因为在您的特定情况下,您希望将2提高到
MaxExponent
幂
2 ** MaxExponent
you can put it as a left shift , but if and only if MaxExponent
is a small positive integer value:你可以把它作为左移,但当且仅当
MaxExponent
是一个小的正整数值:
1 << MaxExponent
Like this像这样
// double: see comments below `1L` stands for `long` and so MaxExponent = [0..63]
public const double MaxValue = MaxMantissa * (1L << MaxExponent);
In general case (when MaxExponent
is an arbitrary double
value), you can try changing const
to readonly
在一般情况下(当
MaxExponent
是任意double
MaxExponent
值时),您可以尝试将const
更改为readonly
public static readonly double MaxValue = MaxMantissa * Math.Pow(2.0, MaxExponent);
You can't, basically (except, as noted, for the trivial case of powers of 2, which can be obtained via the shift operator).基本上你不能(除非,如上所述,对于 2 的幂的微不足道的情况,可以通过移位运算符获得)。
You can hard-code the value and add a comment, or you can use a static readonly
, but note that static readonly
doesn't have the same "bake into the call-site" semantics.您可以对值进行硬编码并添加注释,或者您可以使用
static readonly
,但请注意static readonly
没有相同的“烘焙到调用站点”语义。 In most cases that doesn't present a problem.在大多数情况下,这不会出现问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.