Why does this implicit conversion from int to uint work?(为什么这种从 int 到 uint 的隐式转换有效?)
问题描述
使用 Casting null doesn't compile 作为灵感,来自 Eric Lippert 的评论:
Using Casting null doesn't compile as inspiration, and from Eric Lippert's comment:
这展示了一个有趣的案例.uint x = (int)0;"将即使 int 不能隐式转换为 uint,也会成功.
That demonstrates an interesting case. "uint x = (int)0;" would succeed even though int is not implicitly convertible to uint.
我们知道这不起作用,因为 object
不能分配给 string
:
We know this doesn't work, because object
can't be assigned to string
:
string x = (object)null;
但这确实如此,虽然直觉上它不应该:
But this does, although intuitively it shouldn't:
uint x = (int)0;
当 int
不能隐式转换为 uint
时,为什么编译器允许这种情况?
Why does the compiler allow this case, when int
isn't implicitly convertible to uint
?
推荐答案
整数常量转换被 C# 语言视为非常特殊;这是规范的第 6.1.9 节:
Integer constant conversions are treated as very special by the C# language; here's section 6.1.9 of the specification:
如果常量表达式的值在目标类型的范围内,则可以将 int 类型的常量表达式转换为 sbyte、byte、short、ushort、uint 或 ulong 类型.long 类型的常量表达式可以转换为 ulong 类型,前提是常量表达式的值不是负数.
A constant expression of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type. A constant expression of type long can be converted to type ulong, provided the value of the constant expression is not negative.
这允许您执行以下操作:
This permits you to do things like:
byte x = 64;
否则需要一个丑陋的显式转换:
which would otherwise require an ugly explicit conversion:
byte x = (byte)64; // gross
这篇关于为什么这种从 int 到 uint 的隐式转换有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么这种从 int 到 uint 的隐式转换有效?
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 使用 rss + c# 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01