【发布时间】:2016-04-11 23:50:20
【问题描述】:
我是 C# 新手,我来自 C++。
为什么如果我使用“if else”它可以工作,但如果我使用三元运算符就不行?
我以为是因为第三部分中的“Console.Writeline()”,我用一个普通的作业替换了,但还是有同样的问题。
提前谢谢你!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication8
{
class Board
{
private char[,] board = new char[3, 3];
public void move (int g, int x, int y) //player, x , y position
{
char sign = ' ';
switch (g)
{
case '1':
sign = '0';
break;
case '2':
sign = 'x';
break;
default:
Console.WriteLine("Input Error");
break;
}
//error (x > 1 && x < 4 && y > 1 && y < 4) ? (board[x - 1, y - 1] = sign) : (Console.WriteLine("Error"));
if (x > 1 && x < 4 && y > 1 && y < 4)
{
board[x - 1, y - 1] = sign;
}
else Console.WriteLine("Error");
}
}
class Game
{
static void Main(string[] args)
{
}
}
}
【问题讨论】:
-
“没有”是什么意思?它会做你意想不到的事情吗?如果有,是什么?
-
你必须说“不起作用”是什么意思。您收到错误消息吗?如果是,什么信息?行为是否与您的预期不同?如果是,预期和实际行为是什么?
-
嗯,你是对的。它甚至不编译。我在意大利语中使用 Visual Studio。它说不可能推断出那种条件表达式,因为它不存在“char”到“void”的隐式转换。
-
您是如何尝试编写三元运算符的?如果您尝试过
board[x-1,y-1] = (x > 1 && x < 4 && y > 1 && y < 4) ? sign : 'n',它应该可以工作。如果您刚刚尝试过(x > 1 && x < 4 && y > 1 && y < 4) ? sign : 'n',那么您就有问题了,它不应该这样写。
标签: c# ternary-operator