C#条件运算符错误只有assignment,call,increment,decrement,await,new object expressions可以作为语句使用

C# conditional operator error Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

您好,我正在编写一个基本程序来查找输入数字是否为素数。我有一个 checkPrime(num) 函数来检查素数和 returns true 如果 num 是素数 else returns false。现在,在我的 main() 函数中,我使用了条件运算符来缩短代码,但我收到了一个我不确定的错误。下面是我的代码:

static void Main(String[] args) {
    int n = Int32.Parse(Console.ReadLine());
    while (n-- > 0) {
        int num = Int32.Parse(Console.ReadLine());
        (checkPrime(num) == true) ? Console.WriteLine("Prime") : Console.WriteLine("Not Prime");
    }
}

编译时,我在条件语句行的 while 循环中收到 Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement 错误。我不确定我错过了什么。有一个类似的问题here and people have answered that the conditional operator line is an expression and not a statement so there has to be some sort or assignment for the value of the expression. Same kind of example is given in MSDN reference,其中的解释是这样的

// ?: conditional operator.
classify = (input > 0) ? "positive" : "negative";

但是我无法理解的是在我的函数中我想做的就是检查函数的 return 值然后打印输出。那么在我的案例中,这个表达式是从哪里来的。

conditional operator 是一个 表达式 ,而不是一个语句,这意味着它不能独立存在,因为结果必须以某种方式使用。在您的代码中,您不使用结果,而是尝试产生 副作用

根据 ? 之前的条件,运算符 return 是第一个或第二个表达式的结果。但是 Console.WriteLine() 的 return 类型是 void。所以运算符 与 return 没有任何关系。 void 不是 ?: 运算符的有效 return 类型。所以这里不能使用void-方法。

所以你可以这样做:

while (n-- > 0) {
    int num = Int32.Parse(Console.ReadLine());
    string result = checkPrime(num) ? "Prime" : "Not Prime";
    Console.WriteLine(result);
}

或者您在 Console.WriteLine() 调用中使用运算符:

while (n-- > 0) {
    int num = Int32.Parse(Console.ReadLine());
    Console.WriteLine(checkPrime(num) ? "Prime" : "Not Prime");
}

在这两个示例中,运算符 return 是两个字符串之一,具体取决于条件 。这就是这个运算符的用途。


注意您不需要比较checkPrime()true的结果。结果已经是 bool.