Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在if块中对int进行短转换_C#_Casting - Fatal编程技术网

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。