使用条件(三元)运算符分配lambda表达式

我试图使用条件(三元)运算符将适当的lambda表达式分配给变量,具体取决于条件,但我得到编译器错误: 无法确定条件表达式的类型,因为’lambda表达式之间没有隐式转换’和’lambda表达’ 。 我可以使用常规的if-else来解决这个问题,但是条件运算符对我来说更有意义(在这个上下文中),会使代码更简洁添加,至少,我想知道它为什么没有的原因’工作。

// this code compiles, but is ugly! :) Action hh; if (1 == 2) hh = (int n) => Console.WriteLine("nope {0}", n); else hh = (int n) => Console.WriteLine("nun {0}", n); // this does not compile Action ff = (1 == 2) ? (int n) => Console.WriteLine("nope {0}", n) : (int n) => Console.WriteLine("nun {0}", n); 

C#编译器尝试独立创建lambda,并且无法明确地确定类型。 转换可以通知编译器使用哪种类型:

 Action ff = (1 == 2) ? (Action)((int n) => Console.WriteLine("nope {0}", n)) : (Action)((int n) => Console.WriteLine("nun {0}", n)); 

这会奏效。

 Action ff = (1 == 2) ? (Action)((int n) => Console.WriteLine("nope {0}", n)) : (Action)((int n) => Console.WriteLine("nun {0}", n)); 

这里有两个问题

  1. 表达
  2. 三元运算符

1.表达问题

编译器告诉你到底出了什么问题 – 'Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression'

这意味着你所写的是lambda表达式,结果变量也是lambda表达式。

lambda表达式没有任何特定类型 – 它只能转换为表达式树。

成员访问表达式(您正在尝试执行的操作)仅在表单中可用

 primary-expression . identifier type-argument-list(opt) predefined-type . identifier type-argument-list(opt) qualified-alias-member . identifier type-argument-list(opt) 

……并且lambda表达式不是主要表达式。

2.三元算子的问题

如果我们这样做

 bool? br = (1 == 2) ? true: null; 

这导致错误说与你的完全一样。 'Type of conditional expression cannot be determined because there is no implicit conversion between 'bool' and ''

但如果我们这样做,错误就消失了

 bool? br = (1 == 2) ? (bool?)true: (bool?)null; 

一方的铸造也将起作用

 bool? br = (1 == 2) ? (bool?)true: null; 

要么

 bool? br = (1 == 2) ? true: (bool?)null; 

对于你的情况

 Action ff = (1 == 2) ? (Action)((int n) => Console.WriteLine("nope {0}", n)) : ((int n) => Console.WriteLine("nun {0}", n)); 

要么

 Action ff = (1 == 2) ? ((int n) => Console.WriteLine("nope {0}", n)) : (Action)((int n) => Console.WriteLine("nun {0}", n)); 

事实上,通过类型推断,您可以:

  • 使用var作为局部变量
  • 仅转换三元运算符的第一个表达式
  • 省略lambda参数的类型,因为它可以推断出来

结果更加简洁。 (我让你决定它是否更具可读性。)

  var ff = condition ? (Action)(n => Console.WriteLine("nope {0}", n)) : n => Console.WriteLine("nun {0}", n); 

基本上与其他人一样,以不同的forms回答

 Action ff = (1 == 2) ? new Action(n => Console.WriteLine("nope {0}", n)) : new Action(n => Console.WriteLine("nun {0}", n));