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

在c#中,隐式短到字节是不可能的,但在隐式int短到字节时没有问题。其中源值始终与目标范围一致,c#,type-conversion,C#,Type Conversion,请参阅您的回复:“ 因为short是2字节,byte是1字节,所以即使short值在byte的范围内,它也不会隐式转换为byte 那么,范围内的int值是如何隐式转换并存储在short中的呢?Alexei Levenkov在他的最后一条评论中引用了答案,但也许应该有一些进一步的解释:给变量赋值与给另一个变量赋值不同(特别是如果另一个变量也是另一种类型,这意味着隐式或显式转换) 例如: // The following statement defines a variable // called

请参阅您的回复:“

因为short是2字节,byte是1字节,所以即使short值在byte的范围内,它也不会隐式转换为byte


那么,范围内的int值是如何隐式转换并存储在short中的呢?

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

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

那么,范围内的int值是如何隐式转换并存储在int中的呢?
。你是说
转换并存储在缩写中的
,对吗?是的,你是对的,先生…!我已经编辑了我的输入错误查询。我想你需要提供一个示例。大多数bas都没有隐式转换ic示例(
short v=someIntVariable;
)无法使用“无法将类型“int”隐式转换为“short”。存在显式转换(是否缺少转换?)…肯定需要一个显示问题的转换。请在MSDN上勾选“short”。请编辑您的帖子,以便清楚您到底想问什么(你在评论中有许多问题的变体)。+1.你也可以添加
short shortValue3=42L;
short shortValue4=0x1fff;
,这也会失败。嗨,谢谢feO2x!当你说“给一个变量赋值与给另一个变量赋值不同”时,我很清楚我的疑问抱歉,但是,我在您的答复中发现了另一个查询…为什么将文字指定给变量与从另一个变量指定值不同…这有什么区别…!如果您有时间,只需执行lil查询…如果将文字指定给变量,编译器会将该特定值解释为特定值n键入并将其硬编码到程序集中。编译器可以执行编译时检查,这样做。另一方面,赋值始终在运行时执行,因为在执行赋值时,编译器无法知道某个变量持有哪个特定值。在本例中,如果使用了
int
变量如果将其值赋给
short
变量,那么您可能会看到显式的转换错误(如上面的示例所示)。但当您使用文字时(至少我假设是这样),您会发现
int
short
对文字使用相同的样式(如我的回答中所述)。