在新的开关C#8.0中使用lambda函数返回值

问题描述

我想在代码中使用新的开关,对于方法结果进行日志记录并返回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

我该如何解决

解决方法

问题是您的switch表达式返回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();
   },_     => () =>
   {
      throw new Exception("Unexpected error");
   }
}

return func();