Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在ActionResult ASP.NET Core 2.1中使用空合并运算符_C#_Asp.net Core_Asp.net Core 2.1_Null Coalescing - Fatal编程技术网

C# 如何在ActionResult ASP.NET Core 2.1中使用空合并运算符

C# 如何在ActionResult ASP.NET Core 2.1中使用空合并运算符,c#,asp.net-core,asp.net-core-2.1,null-coalescing,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) re

有人能解释一下为什么我在以下方法的空合并中出现错误:

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'
}  
我不明白的是,为什么第一个返回在不需要任何强制转换的情况下工作,而第二个单行空合并不工作

我的目标是ASP.NET Core 2.1


编辑: 谢谢您的解释,但我不建议在这里使用空合并,因为
NotFound()
在转换后不会返回正确的错误代码


return(ActionResult)products?.FirstOrDefault(p=>p.Id==Id)??NotFound()

发生错误,因为无法强制转换类型

试试这个:

[HttpGet("{id}")]
public ActionResult<Product> GetById(int id)
{
    var result = products?.FirstOrDefault(p => p.Id == id);
    return result != null ? new ActionResult<Product>(result) : NotFound();
}
[HttpGet(“{id}”)]
公共操作结果GetById(int id)
{
var结果=产品?.FirstOrDefault(p=>p.Id==Id);
返回结果!=null?新的ActionResult(结果):NotFound();
}
编辑:

无法编译程序(使用null合并运算符)的原因是返回类型不可竞争。在一种情况下,它返回产品类,否则它返回
ActionResult
。在按照我的建议更新代码之后,我想您将能够使用null合并操作符

2。编辑(回答如下)

在更深入地挖掘这个问题之后,我发现当使用三元if语句或null合并运算符时,我们需要显式地指定当可能返回多个类型时,我们期望从该语句生成什么类型。如前所述,编译器不会在不隐式强制转换的情况下决定返回哪种类型。因此,将返回类型转换为ActionResult解决了这个问题

return (ActionResult<Product>) products.FirstOrDefault(p=>p.id ==id) ?? NotFound();
return(ActionResult)products.FirstOrDefault(p=>p.id==id)??NotFound();

但最好添加如上所示的响应类型属性。

returnproducts.FirstOrDefault(p=>p.Id==Id)??(ActionResult)未找到()应该这样做。@KirkLarkin它将消失编译器警告,但它会正确返回
NotFoundResult
吗?对此我不确定。我不确定您尝试使用此模式是否帮了自己大忙,因为它不会使代码更具可读性。它实现了相反的效果,更难阅读和维护code@Tseng撇开可读性不谈,实际上它会按照他想要的方式工作吗?这是一个紧迫的问题@TanvirArjel:不,它不会按照他想要的方式工作,所有其他方式都比第一次更加冗长,最终会导致代码重复或不必要的显式包装,并
操作结果
/
IActionResult
。所有这些都是为了节省两次换行?他最好在类
OkOrNotFound(result)
上使用helper方法。一个XY问题不是关于这个!他实际上想知道为什么空合并操作符没有在这里编译?对存储库使用try-get模式有点奇怪。Try/Get模式应该只在您通常有抛出异常的方法并且希望(为了性能和可读性)避免Try/catch的情况下使用,例如
int.Parse(…)
vs
int.TryParse(…)
@TanvirArjel很明显,他无法编译,因为返回的产品类不是从ActionResult派生的。因此,类型不匹配。感谢您的帮助,但即使添加了这些属性,我仍然会在空合并中遇到错误。我想我已经找到了正确的答案。正如这里所指定的,当使用三元if语句或null合并运算符时,编译器在选择要返回的类型时会感到困惑。所以将代码更新为return(ActionResult)products.FirstOrDefault(p=>p.id==id)??NotFound();
[HttpGet("{id}")]
public ActionResult<Product> GetById(int id)
{
    var result = products?.FirstOrDefault(p => p.Id == id);
    return result != null ? new ActionResult<Product>(result) : NotFound();
}
[HttpGet("{id}")]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
public ActionResult<Product> GetById(int id)
{
    if (!_repository.TryGetProduct(id, out var product))
    {
        return NotFound();
    }

    return product;
}
[HttpGet("{id}")]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
public ActionResult<Product> GetById(int id)
return (ActionResult<Product>) products.FirstOrDefault(p=>p.id ==id) ?? NotFound();