2012-11-29 60 views
1

我使用这个代码显示的结果为偶数或奇数,而不是真假这里预期:三元操作符不工作

Console.WriteLine(" is " + result == true ? "even" : "odd"); 

因此我使用三元运算符,但它抛出的错误,一些语法问题在这里,但我无法捕捉它。 由于提前

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

    namespace ConsoleApplicationForTesting 
    { 
     delegate int Increment(int val); 
     delegate bool IsEven(int v); 

class lambdaExpressions 
    { 
     static void Main(string[] args) 
     { 

      Increment Incr = count => count + 1; 

      IsEven isEven = n => n % 2 == 0; 


      Console.WriteLine("Use incr lambda expression:"); 
      int x = -10; 
      while (x <= 0) 
      { 
       Console.Write(x + " "); 
       bool result = isEven(x); 
       Console.WriteLine(" is " + result == true ? "even" : "odd"); 
       x = Incr(x); 
      } 
+0

因为在函数中没有返回。你期望从IsEven返回布尔(只是猜测)。 Easiset解决方案,只需在Visual Studio中双击该行,它就会带您进入发生错误的**精确行**。 – Tigran

+0

而错误信息并没有帮助你? – leppie

+0

@leppie,错误是“”运算符'=='不能应用于'string'和'bool'类型的操作数\t“” –

回答

3

试试:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ConsoleApplicationForTesting 
{ 
    delegate int Increment(int val); 
    delegate bool IsEven(int v); 

class lambdaExpressions 
{ 
    static void Main(string[] args) 
    { 

     Increment Incr = count => count + 1; 

     IsEven isEven = n => n % 2 == 0; 


     Console.WriteLine("Use incr lambda expression:"); 
     int x = -10; 
     while (x <= 0) 
     { 
      Console.Write(x + " "); 
      bool result = isEven(x); 
      Console.WriteLine(" is " + (result == true ? "even" : "odd")); 
      x = Incr(x); 
     } 
1

你错过了一个括号:

Console.WriteLine(" is " + (result == true ? "even" : "odd")); 

编译器可能会抱怨,你不能添加一个字符串和一个布尔值。通过添加括号将表达式属性分组,编译器很高兴。你也是。

4

你需要括号。 " is " + (result ? "even" : "odd");

三元运算符有一个较低的优先权,然后concententation(请参阅precendence table at MSDN)。

你原来的代码说联合,然后比较true

4

运算符+的优先级高于==。为了解决这个问题,简单地把括号围绕三元expresion:

Console.WriteLine(" is " + (result == true ? "even" : "odd")); 
2
Console.WriteLine(" is {0}", result ? "even" : "odd"); 
+0

+1好,简单而简单:) – V4Vendetta

3

这是因为operator precedence。你表达

" is " + result == true ? "even" : "odd" 

被解释为

(" is " + result) == true ? "even" : "odd" 

因为+==更高的优先级。使用括号或单独的变量来避免此行为。

" is " + (result == true ? "even" : "odd") 

var evenOrOdd = result == true ? "even" : "odd"; 
... " is " + evenOrOdd ... 
6

看看你所得到的错误:

操作 '==' 不能应用于类型 '字符串' 的操作数和 '布尔'

这是因为缺少括号。它串联字符串和布尔值,这会产生一个字符串值,并且您无法将其与bool进行比较。

要解决它:

Console.WriteLine(" is " + (result == true ? "even" : "odd")); 

进一步澄清。

bool result = true; 
string strTemp = " is " + result; 

上述声明是在一个字符串,is True一个有效的声明和结果,所以你的说法目前看起来像:

Console.WriteLine(" is True" == true ? "even" : "odd"); 

字符串和布尔之间的上述比较是无效的,因此你错误。