C# 在if块中对int进行短转换
我有以下代码:C# 在if块中对int进行短转换,c#,casting,C#,Casting,我有以下代码: Int16 myShortInt; myShortInt = Condition ? 1 :2; 此代码导致编译器错误: 无法将类型“int”隐式转换为“short” 如果我以扩展格式写入条件,则没有编译器错误: if(Condition) { myShortInt = 1; } else { myShortInt = 2; } 为什么会出现编译器错误?之所以会出现错误,是因为默认情况下,文本整数被视为int,而int由于精度
Int16 myShortInt;
myShortInt = Condition ? 1 :2;
此代码导致编译器错误:
无法将类型“int”隐式转换为“short”
如果我以扩展格式写入条件,则没有编译器错误:
if(Condition)
{
myShortInt = 1;
}
else
{
myShortInt = 2;
}
为什么会出现编译器错误?之所以会出现错误,是因为默认情况下,文本整数被视为
int
,而int
由于精度损失而不会隐式转换为short
,因此出现编译器错误。具有小数位数的数字,如1.0
,默认情况下被视为double
此答案详细说明了可用于表示不同文字的修饰符,但遗憾的是,您无法对short
执行此操作:
myShortInt = 1;
Int16 myShortInt;
myShortInt = (short)(Condition ? 1 :2);
因此,您需要显式强制转换int
:
myShortInt = Condition ? (short)1 :(short)2;
或:
在某些情况下,编译器可以为您执行此操作,例如将适合
short
的文本整数值指定给short
:
myShortInt = 1;
Int16 myShortInt;
myShortInt = (short)(Condition ? 1 :2);
不确定为什么没有扩展到三元操作,希望有人能解释其背后的原因。像
1
和2
这样的平面数字默认情况下被视为整数,因此您的?:
返回一个int
,必须转换成short
:
myShortInt = 1;
Int16 myShortInt;
myShortInt = (short)(Condition ? 1 :2);
你可以写:
Int16 myShortInt;
myShortInt = Condition ? (short)1 : (short)2;
或
但是,是的,正如Adam已经回答的,C#将整数文字视为整数,除非在超级简单的情况下,如您所述:
short x = 100;
编译代码时,它看起来像这样: 用于: 看起来有点像
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。
不幸的是,简而言之,您不能这么做。
该死。。。我很确定这里有类似于1s
的东西。。。哦,答案是+1。我猜三元运算符是泛型的;类似于public T操作符?:(bool条件,ta,tb)
,编译器认为在这个例子中T
是int
,因为两个输入都是int
s。