简体   繁体   English

在新开关c# 8.0中使用lambda function返回值

[英]Use lambda function in new switch c# 8.0 to return value

I want to use new switch in my code, that for method result make log and return IActionResult .我想在我的代码中使用新的开关,方法结果 make log 并返回IActionResult

I try to do something like this:我尝试做这样的事情:

var response = (this._coreRepository.Write(value.Content, data.Id.ToString())); \\return bool
return response switch
{
   true => () =>
   {
      this._log.LogInformation("Write is complited");
      return Ok();
   },
   false => () =>
   {
      this._log.LogInformation("Error in writing");
      return BadRequest();
   },
   _     => () =>
   {
      throw new Exception("Unexpected error");
   }
};

But compiler says to me cannot convert lambda expression to type 'IActionResult' because it is not a delegate type .但是编译器对我说cannot convert lambda expression to type 'IActionResult' because it is not a delegate type

How can I fix it?我该如何解决?

The problem is that your switch expression returns a lambda expression but the containing method expects IActionResult .问题是您的 switch 表达式返回lambda expression ,但包含方法需要IActionResult To fix the problem you should rewrite the return statement to immediately invoke result of the switch expression:要解决此问题,您应该重写 return 语句以立即调用 switch 表达式的结果:

var response = (this._coreRepository.Write(value.Content, data.Id.ToString()));

return (response switch
{
   // Here we cast lambda expression to Func<IActionResult> so that compiler
   // can define the type of the switch expression as Func<IActionResult>.
   true => (Func<IActionResult>) (() =>
   {
      this._log.LogInformation("Write is complited");
      return Ok();
   }),
   false => () =>
   {
      this._log.LogInformation("Error in writing");
      return BadRequest();
   },
   _     => () =>
   {
      throw new Exception("Unexpected error");
   }
})(); // () - here we invoke Func<IActionResult>, the result of the switch expression.

If I were you I would rewrite this code the next way to make it easier to read:如果我是你,我会用下一种方式重写这段代码,使其更易于阅读:

var response = (this._coreRepository.Write(value.Content, data.Id.ToString()));

// Now additional braces or casts are not required.
Func<IActionResult> func = response switch
{
   true => () =>
   {
      this._log.LogInformation("Write is complited");
      return Ok();
   },
   false => () =>
   {
      this._log.LogInformation("Error in writing");
      return BadRequest();
   },
   _     => () =>
   {
      throw new Exception("Unexpected error");
   }
}

return func();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM