条件表达式的类型不能确定为

Jak*_*r00 22 c# mono monodevelop

当我在MonoDevelop中编译我的C#项目时,我收到以下错误:

Type of conditional expression cannot be determined as 'byte' and 'int' convert implicitly to each other

代码片段:

byte oldType = type;
type = bindings[type];
//Ignores updating blocks that are the same and send block only to the player
if (b == (byte)((painting || action == 1) ? type : 0))
{
    if (painting || oldType != type) { SendBlockchange(x, y, z, b); } return;
}
Run Code Online (Sandbox Code Playgroud)

这是错误中突出显示的行:

if (b == (byte)((painting || action == 1) ? type : 0))

非常感谢帮助!

Fem*_*ref 29

条件运算符是表达式,因此需要返回类型,并且两个路径都必须具有相同的返回类型.

(painting || action == 1) ? type : (byte)0
Run Code Online (Sandbox Code Playgroud)

  • 如果参数应该是任何类型,例如`String.Format(“ value:{0}”,(value == null)?:“ null”:value),其中value是类型` int?`? (2认同)

Ode*_*ded 5

byte和之间没有隐式转换int,因此您需要在三元运算符的结果中指定一个:

? type : (byte)0
Run Code Online (Sandbox Code Playgroud)

为了工作,此运算符上的两个返回类型都必须相同或定义一个隐式转换。

从MSDN ?: Operator

first_expression和second_expression的类型必须相同,或者必须存在从一种类型到另一种类型的隐式转换。