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 的隐式转换有效?
基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01