c# - 在新开关 c# 8.0 中使用 lambda 函数返回值
问题描述
我想在我的代码中使用新开关,用于方法结果 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
。
我该如何解决?
解决方案
问题是您的 switch 表达式返回 alambda 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();
推荐阅读
- angularjs - iOS 14 中的离子日期时间本地输入中断
- angular - 仅在嵌套表单中禁用 FormControl
- reactjs - 我可以为 React SPA 使用 Microsoft 的脚手架授权/角色(不仅仅是身份验证)吗?
- logstash - logstash 和 grok 将 NUMBER 转换为整数
- sql - 将单个分隔字符串拆分为给定列数的表
- python-3.x - Django - 从变量中导入常量的变量
- outlook - Outlook 图形客户端将类别应用于邮件,但在 UI 中不可见
- c - 更改FREE预处理器定义也将null放入指针
- javascript - JavaScript POO 和 Axios 请求
- python - Python PdfMiner - 如何获取 pdf 中包含的每个单词/句子的方向信息?