c# - 空合并运算符不接受不同类型

我开始,返回一个自定义类:

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

轮次服务中的 Get 方法可以返回 null 并转换为 HTTP 204 No Content。我想知道当我得到 null 时如何返回 404:

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

显然这不起作用,并给我一个 CS0019 错误:Operator '??'不能应用于“Round”和“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() 时那么实际发生的是编译器将使用 implicit operator ActionResult<T> (ActionResult) 改造 NotFoundResult进入ActionResult<Round> .

这在您直接返回值时工作正常,但在三元条件表达式或 null 合并表达式中使用时它将不起作用。相反,您必须自己进行转换:

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

因为 constructor of ActionResult<T> 接受任何 ActionResult , 你可以只传递 NotFoundResult以确保它得到正确转换。

当然,你也可以把它再拆开,让编译器帮你转换:

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

https://stackoverflow.com/questions/60040036/

相关文章:

docker - 我想在正在运行的 docker 容器中使用 docker sdk,并想在正在运行的

kubernetes - 集群上的事件与 kustomize 之间的区别

r - 如何使用 token 在 R 中调用 API

c++ - 错误 : cannot add a default template argument

reactjs - 使用 react-sortable-hoc 拖动时丢失 tr 元素的样式

javascript - 数组中的对象 数组中的对象 数组中的对象 JavaScript - 搜索

javascript - 使用 axios 使用 get 方法发送嵌套的 json 数据

reactjs - SWR vs Isomorphic-unfetch 用于数据获取 Next.Js

awk - 将 'u' 转换为 't' 而无需更改 FASTA 中的 header

javascript - Angular 类型 'split' 上不存在属性 'ArrayBuffe