有人可以解释一下为什么我在以下方法的空合并上遇到错误:
private readonly Product[] products = new Product[];
[HttpGet("{id}")]
public ActionResult<Product> GetById(int id)
{
var product = products.FirstOrDefault(p => p.Id == id);
if (product == null)
return NotFound(); // No errors here
return product; // No errors here
//I want to replace the above code with this single line
return products.FirstOrDefault(p => p.Id == id) ?? NotFound(); // Getting an error here: Operator '??' cannot be applied to operands of type 'Product' and 'NotFoundResult'
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
我不明白的是为什么第一个返回不需要任何强制转换就可以工作,而第二个单行空合并不起作用!
我的目标是 ASP.NET Core 2.1
编辑:
谢谢@Hasan和 @dcastro有关解释,但我不建议在此处使用空合并作为 NotFound()
转换后不会返回正确的错误代码!
return (ActionResult<Product>)products?.FirstOrDefault(p => p.Id == id) ?? NotFound();
最佳答案
OP的问题可以分为两部分:1)为什么建议的空合并表达式无法编译,2)是否有另一种简洁(“单行”)方式在 ASP.NET Core 2.1 中返回结果?
正如 @Hasan 答案的第二次编辑所示, null-coalescing operator 的结果类型根据操作数类型而不是目标类型来解析。因此,OP 的示例失败了,因为 Product
和 NotFoundResult
之间没有隐式转换:
products.FirstOrDefault(p => p.Id == id) ?? NotFound();
@Kirk Larkin 在评论中提到了一种修复该问题的方法,同时保持简洁的语法:
products.FirstOrDefault(p => p.Id == id) ?? (ActionResult<Product>)NotFound();
从 C# 8.0 开始,您还可以使用 switch expression :
products.FirstOrDefault(p => p.Id == id) switch { null => NotFound(), var p => p };
关于c# - 如何将空合并运算符与 ActionResult ASP.NET Core 2.1 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54515704/