C# - 常量值“4294901760”无法转换为“int”
您好,
我不敢相信我问了这么一个基本的问题,但这没有意义,所以就在这里:)。
在 Windows Phone 7 / .net 上的 C# 中,我尝试在类中定义一个常量,如下所示:
// error CS0266: Cannot implicitly convert type 'uint' to 'int'.
// An explicit conversion exists (are you missing a cast?)
public const int RED = 0xffff0000;
如果我像这样在它周围放置 (int) 强制转换,我会收到另一个错误:
// error CS0221: Constant value '4294901760' cannot be converted to a 'int'
// (use 'unchecked' syntax to override)
public const int RED = (int)0xffff0000;
但我知道我的 int 是 32 -bit,因此范围为 -2,147,483,648 到 2,147,483,647,请参见 http://msdn.microsoft.com/en-us/ library/5kzh1b5w(v=vs.80).aspx
那么什么给出了呢?
提前致谢!
猪
Greetings,
I can't believe I'm asking such a basic question, but it doesn't make sense so here it is :).
In C# on Windows Phone 7 / .net, I'm trying to define a constant in a class as follows:
// error CS0266: Cannot implicitly convert type 'uint' to 'int'.
// An explicit conversion exists (are you missing a cast?)
public const int RED = 0xffff0000;
If I put an (int) cast around it like so, I get another error:
// error CS0221: Constant value '4294901760' cannot be converted to a 'int'
// (use 'unchecked' syntax to override)
public const int RED = (int)0xffff0000;
But I know that my int is 32-bit, hence has a range of -2,147,483,648 to 2,147,483,647, see http://msdn.microsoft.com/en-us/library/5kzh1b5w(v=vs.80).aspx
So what gives?
Thanks in advance!
swine
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正如您所注意到的,
Int32
的范围是 -2,147,483,648 到 2,147,483,647,因此可以保存该范围内的任何数字,但只能保存该范围内的数字。 4,294,901,760 大于 2,147,483,647,因此不适合Int32
。对此采取什么措施取决于您想要实现的目标。如果您只想要一个具有位模式
ffff0000
的Int32
,那么按照建议使用unchecked
:y
现在具有值 -65536,这是解释为有符号整数的位模式。然而!如果您确实想要值 4,294,901,760,您应该使用适合它的数据类型 - 所以
UInt32
。As you note, the range of
Int32
is -2,147,483,648 to 2,147,483,647, so any number within that range can be held, but ONLY numbers within that range can be held. 4,294,901,760 is greater than 2,147,483,647, so doesn't fit in anInt32
.What to do about this depends on what you want to achieve. If you just want an
Int32
with the bit patternffff0000
, then as suggested useunchecked
:y
now has the value -65536, which is that bit pattern interpreted as a signed integer.However! If you actually want the value 4,294,901,760 you should use a datatype appropriate to it - so
UInt32
.int
是一个有符号整数,范围从 -2,147,483,648 到 2,147,483,647。您想要的是一个无符号整数,即
uint
,就像第一条错误消息告诉您的那样。int
is a signed integer ranging from -2,147,483,648 to 2,147,483,647.What you want is an unsigned integer, i.e.
uint
, just like the first error message tells you.尝试按照编译器消息的建议使用 unchecked:
这将 RED 定义为 -65536,即 0xffff0000 解释为有符号 int。
Try using unchecked as suggested by the compiler message:
This defines
RED
as -65536, which is 0xffff0000 interpreted as signed int.这应该可以帮助您解决未经检查的问题:
This should get you around the unchecked: