为什么这种从 int 到 uint 的隐式转换有效? [英] Why does this implicit conversion from int to uint work?

查看:43
本文介绍了为什么这种从 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 的隐式转换有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆