问题描述
1)如果一个操作数的类型为 ULONG
,而另一个操作数的类型为为sbyte /短路/ INT /长
,然后编译时错误。我看不出这个逻辑。因此,为什么会是坏主意,而不是促进两个操作数键入双击
或浮动
?
1) If one operand is of type ulong
, while the other operand is of type sbyte/short/int/long
, then compile-time error occurs. I fail to see the logic in this. Thus, why would it be bad idea for both operands to instead be promoted to type double
or float
?
long L = 100;
ulong UL = 1000;
double d = L + UL; // error saying + operator can't be applied
to operands of type ulong and long
b)编译器隐>转换 INT
文字到字节
b :
b) Compiler implicitly converts int
literal into byte
type and assigns resulting value to b
:
byte b = 1;
但是,如果我们试图赋予文字类型的 ULONG
键入长
(或类型 INT
,字节
等),则编译器会报告错误:
But if we try to assign a literal of type ulong
to type long
(or to types int
, byte
etc), then compiler reports an error:
long L = 1000UL;
我想编译器将能够找出常量表达式的结果是否可以融入型变量长
?
感谢您
推荐答案
要回答标记问题(1) - 添加符号和无符号多头可能是一个的错误的。如果开发者的意图是溢入的不精确的在这种情况下算术那么这东西,他们应该明确做的,通过转换两个参数翻番。这样做含蓄是的隐藏的错误的往往比它的做正确的事的
To answer the question marked (1) -- adding signed and unsigned longs is probably a mistake. If the intention of the developer is to overflow into inexact arithmetic in this scenario then that's something they should do explicitly, by casting both arguments to double. Doing so implicitly is hiding mistakes more often than it is doing the right thing.
要回答这个问题标记(二) - 当然,编译器可以明白这一点。显然,这不能因为它这样做的整数文字。但同样,这几乎可以肯定是一个错误。如果你的目的是使一个符号长那么的你为什么把它标记为未签名的?这看起来像一个的错误的。 C#经过精心设计,使它看起来怪异的图案像这一点,并提请你注意他们,而不是使一个猜测你的意思是说这奇怪的事情,领先的炽烈仿佛一切正常。编译器试图鼓励你写出正确的代码; 明智的代码不调匀符号和无符号类型即可。
To answer the question marked (b) -- of course the compiler could figure that out. Obviously it can because it does so for integer literals. But again, this is almost certainly an error. If your intention was to make that a signed long then why did you mark it as unsigned? This looks like a mistake. C# has been carefully designed so that it looks for weird patterns like this and calls your attention to them, rather than making a guess that you meant to say this weird thing and blazing on ahead as if everything were normal. The compiler is trying to encourage you to write sensible code; sensible code does not mix signed and unsigned types.
这篇关于相反的错误,为什么不两个操作数升职漂浮或翻番?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!