【问题标题】:Azure Function return object type castingAzure 函数返回对象类型转换
【发布时间】:2020-01-14 12:09:39
【问题描述】:

尝试理解 Azure Function 中的默认 return 代码

return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");

这取决于name 值将执行: 如果namenull

return new BadRequestObjectResult("Please pass a name on the query string or in the request body");

否则:

return (ActionResult)new OkObjectResult($"Hello, {name}")

我的问题:

  1. 为什么OkObjectResult 使用了类型转换,而BadRequestObjectResult 却没有?
  2. 为什么我们甚至需要为OkObjectResult 投射?

【问题讨论】:

    标签: c# azure-functions


    【解决方案1】:

    如果你这样做了......

    if(name != null)
    {
      return new OkObjectResult($"Hello, {name}");
    }
    else
    {
      return new BadRequestObjectResult("Please pass a name on the query string or in the request body");
    }
    

    ...不需要强制转换。

    类型转换对于您的问题中的代码行是必要的,因为它使用了 三元运算符(即a ? b : c)。使用三元运算符时,谓词后面的两个元素(bc)必须共享一个类型。 OkObjectResultBadRequestObjectResult 是两种不同的类型,所以没有演员表,这是不可接受的。

    但是,bc 都继承自 ActionResult。通过将OkObjectResult 转换为ActionResultBadRequestObjectResult 元素变得可以接受,因为它也是ActionResult 类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-07
      • 1970-01-01
      • 2013-01-09
      • 2021-05-01
      • 1970-01-01
      • 2018-07-24
      相关资源
      最近更新 更多