条件表达式的类型无法确定

24

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

条件表达式的类型无法确定为“byte”,而“int”可以隐式转换为它

代码段:

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;
}

以下是报错中被突出显示的代码行:

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

非常感谢您的帮助!

2个回答

32

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

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

2
如果参数预期为任何类型,例如 String.Format("value: {0}", (value == null) ? : "null" : value),其中 value 的类型为 int?,该怎么办? - mr5

5

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

? type : (byte)0

这个运算符的两个返回类型必须相同或者存在隐式转换才能正常工作。

来自MSDN ?: 运算符:

第一个表达式和第二个表达式的类型必须相同,或者存在一种类型到另一种类型的隐式转换。


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