C#字节类型和文字 [英] C# byte type and literals

查看:60
本文介绍了C#字节类型和文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码有效.

byte b = 1;

但是我注意到以下代码不起作用

But I noticed the following code doesn't work

byte b = BooleanProperty ? 2 : 3; // error

编译器说

无法将源类型"int"转换为目标类型"byte"

Cannot convert source type 'int' to target type 'byte'

我知道int类型不能隐式转换为字节类型.但是为什么前一种代码有效,而后者却无效呢?

I understand that int type cannot be converted to byte type implicitly. But why the former code works, and the latter doesn't?

推荐答案

int constants 有一个隐式转换(不仅是文字,而且是任何编译时常量表达式(值类型为 int )到 byte (只要该值在范围内).这来自C#5规范的6.1.9节:

There's an implicit conversion from int constants (not just literals, but any compile-time constant expression of type int) to byte, so long as the value is in range. This is from section 6.1.9 of the C# 5 specification:

隐式常量表达式转换允许以下转换:

An implicit constant expression conversion permits the following conversions:

  • 可以将类型为 int 的常量表达式(第7.19节)转换为类型为 sbyte byte short code>, ushort uint ulong ,只要常量表达式的值在目标类型的范围内即可.
  • A constant-expression (§7.19) 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.

但是,没有从常规"关键字隐式转换.类型为 int byte 的表达式-这就是第二种情况.有点像这样:

However, there's no implicit conversion from a "general" expression of type int to byte - and that's what you've got in your second case. It's a bit like this:

int tmp = BooleanProperty ? 2 : 3;
byte b = tmp; // Not allowed

请注意,条件表达式的 use 在推断其 type 中没有任何作用-并且第二和第三操作数均为类型int ,整个表达式的类型也为 int .

Note that the use of the conditional expression doesn't play any part in inferring its type - and as both the second and third operands are of type int, the overall expression is of type int as well.

因此,如果您理解了为什么我将代码分成两个语句的上面的代码片段无法编译,那就说明了为什么带条件的单行版本也不会编译.

So if you understand why the snippet above where I've separated the code into two statements doesn't compile, that explains why your single-line version with the conditional doesn't either.

有两种修复方法:

  • 将第二和第三操作数更改为 byte 类型的表达式,以便条件表达式的整体类型为 byte :

  • Change the second and third operands to expressions of type byte so that the conditional expression has an overall type of byte:

  byte b = BooleanProperty ? (byte) 2 : (byte) 3;

  • 投射条件表达式的结果:

      byte b = (byte) (BooleanProperty ? 2 : 3);
    

  • 这篇关于C#字节类型和文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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