在if语句块中将short类型转换为int类型

8

I have the following code:

Int16 myShortInt;  
myShortInt = Condition ? 1 :2;

这段代码会导致编译器错误:

无法隐式将类型'int'转换为'short'

如果我按照展开的格式编写条件,就不会出现编译器错误:

if(Condition)  
{  
   myShortInt = 1;  
}  
else  
{  
   myShortInt   = 2;  
} 

为什么会出现编译器错误?
4个回答

7
您之所以会出现错误,是因为字面整数默认被视为int,而int不会隐式地转换为short,因为这会导致精度损失-因此编译器会报错。带有小数点的数字,例如1.0,默认情况下被视为double

此答案详细介绍了可用于表示不同文字的修饰符,但不幸的是,您无法对short进行此操作:

C# short/long/int literal format?

因此,您需要显式转换您的int

myShortInt = Condition ? (short)1 :(short)2;

或者:

myShortInt = (short)(Condition ? 1 :2);


有时编译器可以为您完成此操作,例如将适合short的文字整数值分配给short:

myShortInt = 1;

不确定为什么这个没有被扩展到三元操作,希望有人能解释一下背后的原因。


很遗憾,您不能这样做,因为短整型不支持此操作。该死...我一直以为有像"1s"这样的短整型...好吧,答案加一分。 - Nolonar

1

12 这样的平面数字默认情况下被视为整数,因此您的 ?: 返回一个 int,必须将其转换为 short

Int16 myShortInt;  
myShortInt = (short)(Condition ? 1 :2);

0
你可以写成这样:
Int16 myShortInt;  
myShortInt = Condition ? (short)1 : (short)2;

或者

myShortInt = (short) (Considiton ? 1 : 2);

但是,正如Adam已经回答的那样,C#将整数字面量视为int,除了像你所述的超级简单的情况:

short x = 100;

0
当代码被编译时,它看起来像这样:
for:
Int16 myShortInt;  
 myShortInt = Condition ? 1 :2;

它看起来像这样
Int16 myShortInt; 
var value =  Condition ? 1 :2; //notice that this is interperted as an integer.
myShortInt = value ;

当循环:

if(Condition)  
{  
 myShortInt = 1;  
}  
else  
{  
 myShortInt   = 2;  
} 

在这之间没有将值解释为int的阶段,而字面量被视为Int16。


我猜三元运算符是通用的,类似于 public T operator ?:<T> (bool condition, T a, T b),编译器认为此处的 T 是一个 int,因为两个输入都是 int - Nolonar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接