C# Azure函数返回对象类型转换

C# Azure函数返回对象类型转换,c#,azure-functions,C#,Azure Functions,试图理解Azure函数中的默认返回代码 return name != null ? (ActionResult)new OkObjectResult($"Hello, {name}") : new BadRequestObjectResult("Please pass a name on the query string or in the request body"); 这取决于名称值将执行: 如果name为null: return new BadRequestObjectResult("P

试图理解Azure函数中的默认
返回
代码

return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
这取决于
名称
值将执行: 如果
name
null

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

return (ActionResult)new OkObjectResult($"Hello, {name}")
我的问题是:

  • 为什么有类型转换用于
    OkObjectResult
    ,而不用于
    BadRequestObjectResult
  • 为什么我们甚至需要为
    OkObjectResult
    进行强制转换
  • 如果你这么做了

    if(name!=null)
    {
    返回新的OkObjectResult($“Hello,{name}”);
    }
    其他的
    {
    返回新的BadRequestObjectResult(“请在查询字符串或请求正文中传递名称”);
    }
    
    …不需要铸造

    由于使用了三元运算符(即
    a?b:c
    ),因此在您的问题中的代码行上进行类型转换是必要的。使用三元运算符时,谓词(
    b
    c
    )后面的两个元素必须共享一个共同的类型
    OkObjectResult
    BadRequestObjectResult
    是两种不同的类型,因此如果没有强制转换,这是不可接受的

    但是,
    b
    c
    都继承自
    ActionResult
    。通过将
    OkObjectResult
    强制转换为
    ActionResult
    ,可以接受
    BadRequestObjectResult
    元素,因为它也是
    ActionResult
    类型