在此代码中,我有如下要求:
decimal col;
if (condition)
{
(decimal)col = (decimal)col | ((decimal)System.Math.Pow(2, 0));
}
编译此代码时,出现错误
Operator | cannot be applied to operands of type 'decimal' and 'decimal'
有人可以解释一下吗?谢谢
答案 0 :(得分:7)
正如编译时错误所示,您无法在|
上使用decimal
。 decimal
类型适用于12.34
等数字。如果您只使用12
或34
这样的数字,那么您最好使用int
(介于±20亿之间)或long
之间(介于±9之间)你的整数有多大。
任何提升到幂零的数字, n 0 等于1
,因此Math.Pow(2, 0)
可以替换为1
。
您的代码可能看起来像这样,将编译。
int col;
和
if (condition)
col = col | 1;
最后,您可能更喜欢使用三元运算符?:
来嵌入您的if
语句,在您的情况下执行哪个更具可读性:
col = condition ? (col | 1) : col;
如果您需要使用 REALLY BIG 整数,那么就有一个类! System.Numerics.BigInteger
(System.Numerics.dll
)。
BigInteger类型是一个不可变类型,表示一个任意大的整数,其理论上的值没有上限或下限。
您的声明将成为:
BigInteger col;
你的按位操作正常。
查看项目IntX
IntX是一个用纯C#2.0编写的任意精度整数库,具有快速 - 约O(N * log N) - 乘法/除法算法实现。它提供了对整数的所有基本算术运算,比较,按位移位等。
答案 1 :(得分:-1)
将其投放到Int64
,然后应用|
运营商。
decimal d1 = ..;
decimal d2 = ..;
var res = (long)d1 | (long)d2;