簡體   English   中英

空合並運算符不接受不同類型

[英]The null-coalescing operator doesn't accepts different types

我開始,返回一個自定義類:

[HttpGet()]
public ActionResult<Round> Get(string id) =>
    this._roundsService.Get(id);

rounds 服務中的 Get 方法可以返回 null 並轉換為 HTTP 204 No Content。 我想知道當我得到空值時如何返回 404:

[HttpGet()]
public ActionResult<Round> Get(string id) =>
    this._roundsService.Get(id) ?? NotFound();

顯然這不起作用並給我一個 CS0019 錯誤: Operator '??' cannot be applied to operands of type 'Round' and 'NotFoundResult' Operator '??' cannot be applied to operands of type 'Round' and 'NotFoundResult'

我對其他單行程序持開放態度,如果不為空則返回所需的對象,如果為空則返回 404。

我將 C# 8.0 與 netcoreapp3.0 框架一起使用。 我還沒有啟用可為空功能。 這可能是導致問題的原因嗎?

以防萬一,這里是服務類中的方法:

public Round Get(string id) =>
    this._rounds.Find(round => round.Id == id).FirstOrDefault();

當您調用NotFound() ,您正在創建一個NotFoundResult 您的方法具有ActionResult<Round>的返回類型,但NotFoundResult實際上並未從ActionResult<Round>繼承,因此您不能直接返回NotFoundResult對象。

當您鍵入return NotFound() ,實際發生的是編譯器將使用隱式運算符ActionResult<T> (ActionResult)NotFoundResult轉換為ActionResult<Round>

這在您直接返回值時工作正常,但在三元條件或空合並表達式中使用時將不起作用。 相反,您必須自己進行轉換:

public ActionResult<Round> Get(string id) =>
    this._roundsService.Get(id) ?? new ActionResult<Round>(NotFound());

因為ActionResult<T>構造函數接受任何ActionResult ,您只需將NotFoundResult傳遞給它以確保它被正確轉換。

當然,您也可以將其再次拆分並讓編譯器為您進行轉換:

public ActionResult<Round> Get(string id)
{
    var result = this._roundsService.Get(id);
    if (result != null)
        return result;
    return NotFound();
}

當然它不能那樣做。 它只是if簡寫。 我認為相當於你寫的將圍繞這個:

ActionResult<Round> result = this._roundsService.Get(id);
if(result == null)
  result = NotFound();
return result;

在這一點上,編譯器真的很困惑為什么您嘗試將“NotFound()”返回值分配給 ActionResult 變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM