具有负号的无符号整数字面量 [英] Unsigned Integer Literal Having Negative Sign
问题描述
今天我遇到了这种奇怪的行为,有人可以解释为什么会发生这种情况吗?
Today I came a cross this strange behaviour, could someone explain why it happens?
var x = -1U; // When using -1UL it complains though.
Console.WriteLine(x.GetType().Name);
Console.WriteLine(x);
输出:
Int64
-1
MSDN说:
如果文字以U或u结尾,则具有可以表示其值的第一种类型:uint,ulong.
If the literal is suffixed by U or u, it has the first of these types in which its value can be represented: uint, ulong.
https://msdn.microsoft.com/en-us/library/aa664674%28v = vs.71%29.aspx
推荐答案
您的困惑源于您将其解释为数字 -1
,后接 U
.它实际上是数字 1U
的否定-
.如问题中的引号所示,该数字 1U
的类型为 uint
.取反 uint
会产生 long
.
Your confusion stems from you interpreting this as the number -1
, followed by a suffix U
. It's actually the negation -
of the number 1U
. That number 1U
has type uint
, as indicated by the quote in your question. Negating an uint
produces a long
.
这篇关于具有负号的无符号整数字面量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!