在新的 switch c# 8.0 中使用 lambda 函数到 return 值

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

我想在我的代码中使用新开关,方法结果 make log 和 return IActionResult.

我试着做这样的事情:

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");
   }
};

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

我该如何解决?

问题是您的开关表达式 return 是 lambda expression,但包含方法需要 IActionResult。要解决此问题,您应该重写 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.

如果我是你,我会用下一种方式重写这段代码以使其更易于阅读:

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