在 c# 中,隐式短到字节是不可能的,但在隐式 int 到短时没有问题.其中源值始终与目标范围一起

本文关键字:范围 一起 有问题 目标 int 到字节 不可能 | 更新日期: 2023-09-27 18:18:08

ref. 到您的回复:"在 C# 中从短转换为字节时会发生什么?

您说由于短是 2 个字节,字节是 1 个字节,因此即使短值在字节范围内,它也不会隐式转换为字节。

那么为什么在范围内 int 值被隐式转换并存储在短时间内呢?

在 c# 中,隐式短到字节是不可能的,但在隐式 int 到短时没有问题.其中源值始终与目标范围一起

Alexei Levenkov在他的最后一条评论中引用了答案,但也许应该有一些进一步的解释:将文字分配给变量与从另一个变量分配值不同(特别是如果另一个变量也是另一种类型,这意味着隐式或显式转换(。

例如:

// The following statement defines a variable
// called 'integerValue' and assigns the
// 32 bit signed integer value fourty-two to 
// it because of the literal '42'.
int integerValue = 42;
// The next statement defines a variable
// called 'longValue' and assigns the
// 64 bit signed integer value forty-two to
// it because of the literal '42L'
long longValue = 42L;
// The next line defines a variable
// with the 16 bit signed integer value
// forty-two (literal '42') - the compiler
// will automatically interpret the literal
// in the correct format
short shortValue1 = 42;
// There is no implicit conversion between
// int and short, therefore the next statement
// will not compile. Notice that there is no
// literal involved here - instead a value from
// another variable is assigned. 
short shortValue2 = integerValue; // Error
// The following assignment is also not correct as
// '42L' is not a suitable literal for values of
// type short
short shortValue3 = 42L; // Error

最主要的是,intshort对文字使用相同的样式(纯数字,没有后缀(,这可能会让人们感到困惑。