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

Condition ? : operator in C#

我的 ?: 运算符有问题,所以我尝试了 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();
        }
    }
}

我在某处犯了一个错误,但是哪里如何超出了我的范围。

?: 不是 if then else

The conditional operator

The conditional operator ?:, also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false

此外,Console.WriteLine 没有 return 结果,它是一个有副作用的无效方法。所以它不能与运算符一起使用,句号。

简而言之,只需使用 if then else

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

三元表达式不适合您的情况,因为 Console.WriteLine returns 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?");
}