使用条件(三元)运算符分配lambda表达式 [英] Assign a lambda expression using the conditional (ternary) operator
问题描述
我试图根据条件,使用条件(三元)运算符将正确的lambda表达式分配给变量,但出现编译器错误:无法确定条件表达式的类型,因为没有"lambda表达式"和"lambda表达式"之间的隐式转换.我可以使用常规的if-else来解决此问题,但条件运算符对我而言(在这种情况下)更有意义,至少会使代码更简洁,至少,我想知道为什么它不起作用.工作.
I am trying to use the conditional (ternary) operator to assign the proper lambda expression to a variable, depending on a condition, but I get the compiler error: Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression'. I can use the regular if-else to solve this problem, but the conditional operator makes more sense to me (in this context), would make the code more concise add, at least, I would like to know the reasons why it doesn't work.
// this code compiles, but is ugly! :)
Action<int> 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<int> ff = (1 == 2)
? (int n) => Console.WriteLine("nope {0}", n)
: (int n) => Console.WriteLine("nun {0}", n);
推荐答案
C#编译器尝试独立创建lambda,因此不能明确确定类型.强制转换可以通知编译器使用哪种类型:
The C# compiler tries to create the lambdas independently and cannot unambiguously determine the type. Casting can inform the compiler which type to use:
Action<int> ff = (1 == 2)
? (Action<int>)((int n) => Console.WriteLine("nope {0}", n))
: (Action<int>)((int n) => Console.WriteLine("nun {0}", n));
这篇关于使用条件(三元)运算符分配lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!