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 的隐式转换有效?
基础教程推荐
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 如果条件可以为空 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 将数据集转换为列表 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
