C# Azure函数返回对象类型转换
试图理解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
返回代码
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
类型