c# - 如何将空合并运算符与 ActionResult ASP.NET Core 2.1 一起使用

标签 c# asp.net-core asp.net-core-2.1 null-coalescing

有人可以解释一下为什么我在以下方法的空合并上遇到错误:

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 的示例失败了,因为 ProductNotFoundResult 之间没有隐式转换:

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/

相关文章:

c# - 向窗口句柄发送消息

c# - 尽管 Comparer.Equals 返回 true,但字典不包含键

asp.net - 角色动态授权 asp.net core

c# - 通过 nuget 安装时引用 Bootstrap 的问题

c# - Web Essentials 浏览器链接在 asp mvc 6 项目中不起作用

c# - EF 核心 2.1 中的 COUNT(DISTINCT *)

c# - 正则表达式 .net 拆分

c# - 提供程序 : Named Pipes Provider, 错误 : 40 - Could not open a connection to SQL Server, pgsql

asp.net-core-2.1 - 请求中指定的 Azure AD 回复 url 的 ASP.NET Core Web 应用与配置的回复 url 不匹配

angular - 如何将用户身份验证添加到 .NET Core 2.1 Angular 应用程序?