健康)状况 ? :C#中的运算符

时间:2020-05-07 01:57:51

标签: c# conditional-operator

我对?:运算符有疑问,所以我尝试了if-else块,一切正常。但是当使用 other 运算符时,它将停止工作。

using System;

namespace firstGame
{
    class Program 
    {
        public string playerName;
        public int playerScore;
        public int gameNumber;
        public int playerGuess;

        public void GameStart()
        {
            string r;
            Console.WriteLine("Welcome to my first game");
            Console.Write("please enter your gamer name : ");

            this.playerName= Console.ReadLine();

            do
            {    
                this.gameNumber = Convert.ToInt16(new Random().Next(0,10));
                this.playerScore = 1;

                if (this.playerScore == 1)
                {
                    Console.WriteLine("Guess the hidden number between (1-10)");

                    do
                    {
                        Console.Write("guess number {0} :: ", this.playerScore);
                        string num = Console.ReadLine();

                        int.TryParse(num, out _) ? this.playerGuess=Convert.ToInt16(num) : Console.WriteLine("Are you sure it is a number !!?") ;
                        this.playerScore++;
                    } while (this.playerGuess != this.gameNumber);

                    Console.WriteLine("BINGO {0} is the correct number", this.gameNumber);
                    Console.Write("would you like a new lvl ? (Y/N) :: ");  r=Console.ReadLine();
                }
                else 
                { 
                    this.playerScore = 0; 
                    break; 
                }
            } while (r=="Y");
        }

        static void Main(string[] args)
        {
            new Program().GameStart();
        }
    }
}

我在某个地方犯了一个错误,但在我身外却犯了一个错误。

2 个答案:

答案 0 :(得分:2)

使用cond ? exp1 : exp2时,exp1exp2必须具有相同的类型。

三元表达式不适用于您的情况,因为Console.WriteLine返回void,但是赋值表达式为int

改用传统的 if-else

要修复

// ERROR: This doesn't compile
int.TryParse(num, out _) ? this.playerGuess=Convert.ToInt16(num) : Console.WriteLine("ar you sure it is a number !!?") ;

应该成为

if (int.TryParse(num, out _)) {
    this.playerGuess = Convert.ToInt16(num)
} else {
    Console.WriteLine("ar you sure it is a number !!?");
}

奖金提示:

您实际上可能想要这样:

if (int.TryParse(num, out int val)) {
    this.playerGuess = val;
} else {
    Console.WriteLine("Are you sure it is a number?");
}

答案 1 :(得分:0)

?:不是 if else else

The conditional operator

条件运算符?:,也称为三元条件运算符 运算符,计算一个布尔表达式并返回一个的结果 两个表达式中的一个,具体取决于布尔表达式 评估为真或假

此外,Console.WriteLine不返回结果,它是一个无效方法,具有副作用。因此,它不能与运算符(句号)一起使用。

简而言之,只需先使用,否则再使用