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 的隐式转换有效?
基础教程推荐
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
