在if块中将short转换为int

Nap*_*ies 8 c# casting

我有以下代码:

Int16 myShortInt;  
myShortInt = Condition ? 1 :2;
Run Code Online (Sandbox Code Playgroud)

此代码导致编译器错误:

不能将'int'类型转换为'short'

如果我以扩展格式编写条件,则没有编译器错误:

if(Condition)  
{  
   myShortInt = 1;  
}  
else  
{  
   myShortInt   = 2;  
} 
Run Code Online (Sandbox Code Playgroud)

为什么我会收到编译器错误?

Ada*_*rth 7

您得到错误,因为int默认情况下将文字整数视为默认值,int并且short由于精度损失而不会隐式转换为 - 因此编译器错误.具有小数位的数字,例如默认情况下1.0被视为double.

这个答案详细说明了可用于表达不同文字的修饰符,但不幸的是你不能这样做short:

C#short/long/int文字格式?

所以你需要明确地投射你的int:

myShortInt = Condition ? (short)1 :(short)2;
Run Code Online (Sandbox Code Playgroud)

要么:

myShortInt = (short)(Condition ? 1 :2);
Run Code Online (Sandbox Code Playgroud)


有些时候,编译器可以为你做这个,比如说给里面一个适合文字的整数值shortshort:

myShortInt = 1;
Run Code Online (Sandbox Code Playgroud)

不知道为什么没有扩展到三元行动,希望有人可以解释背后的原因.


Avi*_*ner 0

当代码被编译时,它看起来像这样:

为了:

Int16 myShortInt;  
 myShortInt = Condition ? 1 :2;
Run Code Online (Sandbox Code Playgroud)

它看起来像

Int16 myShortInt; 
var value =  Condition ? 1 :2; //notice that this is interperted as an integer.
myShortInt = value ;
Run Code Online (Sandbox Code Playgroud)

而对于:

if(Condition)  
{  
 myShortInt = 1;  
}  
else  
{  
 myShortInt   = 2;  
} 
Run Code Online (Sandbox Code Playgroud)

中间没有任何阶段将值解释为 int,并且文字被视为 Int16。