分配使用条件(三元)运算符[重复] lambda表达式(Assign a lambda expres

2019-06-25 23:48发布

这个问题已经在这里有一个答案:

  • 怎样才能使用条件三元运算符分配函数求<>有条件的lambda之间? 3个回答

我想使用条件(三元)运算符到适当的lambda表达式分配给一个变量,根据条件,但我得到的编译器错误: 无法确定条件表达式的类型,因为那里是“lambda表达式之间不存在隐式转换'和‘lambda表达式’。 我可以使用常规的if-else来解决这个问题,但是有条件的经营者更有意义,我(在这方面),将会使代码更简洁加,至少,我想知道原因,为什么它不”将不起作用。

// 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);

Answer 1:

C#编译器试图独立地创建lambdas和不能明确地确定的类型。 铸造可以告诉编译器哪种类型的使用方法:

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


Answer 2:

这将工作。

Action<int> ff = (1 == 2)
? (Action<int>)((int n) => Console.WriteLine("nope {0}", n))
: (Action<int>)((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 '<null>'

但是,如果我们做到这一点错误消失

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

一个侧面的铸造也将工作

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

要么

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

对于你的情况

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

要么

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


Answer 3:

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

  • 使用VAR的局部变量
  • 只有投三元运算符的第一表达
  • 省略拉姆达参数的类型,因为它可以推断

其结果是更准确。 (我让你决定它是否更具可读性。)

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


Answer 4:

基本上相同的答案其他人,以不同的形式

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


文章来源: Assign a lambda expression using the conditional (ternary) operator [duplicate]
标签: c# lambda