I have the following code:
Int16 myShortInt;
myShortInt = Condition ? 1 :2;
这段代码会导致编译器错误:
无法隐式将类型'int'转换为'short'
如果我按照展开的格式编写条件,就不会出现编译器错误:
if(Condition)
{
myShortInt = 1;
}
else
{
myShortInt = 2;
}
为什么会出现编译器错误?
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;
不确定为什么这个没有被扩展到三元操作,希望有人能解释一下背后的原因。
像 1
和 2
这样的平面数字默认情况下被视为整数,因此您的 ?:
返回一个 int
,必须将其转换为 short
:
Int16 myShortInt;
myShortInt = (short)(Condition ? 1 :2);
Int16 myShortInt;
myShortInt = Condition ? (short)1 : (short)2;
或者
myShortInt = (short) (Considiton ? 1 : 2);
但是,正如Adam已经回答的那样,C#将整数字面量视为int,除了像你所述的超级简单的情况:
short x = 100;
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