使用条件运算符结合 IsAjaxRequest 返回 ActionResult

发布于 2024-08-12 08:51:04 字数 543 浏览 10 评论 0原文

由于 Mvc.JsonResultMvc.ViewResult 之间没有隐式转换,我不能只使用条件运算符,而是以强制转换结束。

这让我想到了我的问题是,我对 JsonResult 进行装箱所带来的性能损失是值得的,还是我应该只执行一个普通的 if...else 块?

下面的代码出现在正常的控制器操作中: public ActionResult Inactivate()

No Boxing

if (Request.IsAjaxRequest())
{
    return Json(foo);
}
else
{
    return View(bar);
}

VS Boxing

return Request.IsAjaxRequest() ? (ActionResult)Json(foo) : View(bar);

Since there is no implicit conversion between Mvc.JsonResult and Mvc.ViewResult I cannot just utilize a conditional operator but instead end up with a cast.

Which leads me to my question is the performance hit I will take for boxing the JsonResult worth it or should I just do a normal if...else block?

The code below appears inside a normal controller action: public ActionResult Inactivate()

No Boxing

if (Request.IsAjaxRequest())
{
    return Json(foo);
}
else
{
    return View(bar);
}

VS Boxing

return Request.IsAjaxRequest() ? (ActionResult)Json(foo) : View(bar);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

把时间冻结 2024-08-19 08:51:04

您可以选择更适合您的方式。不应该对性能产生影响,所以这只是编码风格和清晰度的问题。

在第二个示例中,您需要转换 Json(foo) 或 View(bar)。这是因为 ?: 运算符需要知道其参数的类型,并且它不够智能,无法找出公共基类型。这严格来说是编译时的事情,对性能没有影响。

此外,这里没有拳击比赛。 JsonResult 和 ViewResult 都是类,而不是结构体,因此它们都已经在堆上。

即使有拳击比赛,我也怀疑它会对表现产生任何真正的影响。 ASP.NET MVC 在幕后进行反射,这比装箱要昂贵得多。

You can do whichever works better for you. There should be no performance impact, so it's just a matter of coding style and clarity.

In your second example, you need to cast either the Json(foo) or the View(bar). This is because the ?: operator needs to know the type of its arguments, and it's not smart enough to figure out the common base type. That's strictly a compile-time thing and it has no effect on performance.

Also, there's no boxing happening here. JsonResult and ViewResult are both classes, not structs, so they are both already on the heap.

Even if there were boxing, I doubt it would have any real impact on performance. ASP.NET MVC is doing reflection behind the scenes, and that's way more expensive than boxing.

凑诗 2024-08-19 08:51:04

我认为 JsonResult 和 ViewResult 都继承自 ActionResult,因此不需要强制转换。在“No Boxing”代码块中,您需要从 Json 和 View 中返回关键字。

I think JsonResult and ViewResult both inherit from ActionResult, so no casting is necessary. In your "No Boxing" code block, you need the keyword return in from of Json and View.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文