【问题标题】:Can a non-nullable int be null? [duplicate]不可为空的 int 可以为空吗? [复制]
【发布时间】:2017-03-07 05:52:17
【问题描述】:

我修改了 ASP.NET Identity 2.0 Extending Identity Models 以便使用 int 键而不是字符串 (GUID),如 ASP.NET Identity 2.0 Extending Identity Models and Using Integer Keys Instead of Strings 所示,并修改了一些方法的逻辑,如下所示:

public async Task<ActionResult> Details(string id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    var user = await UserManager.FindByIdAsync(id);
    ViewBag.RoleNames = await UserManager.GetRolesAsync(user.Id);
    return View(user);
}

到这里:

public async Task<ActionResult> Details(int id)
{
    if (id > 0)
    {
        // Process normally:
        var user = await UserManager.FindByIdAsync(id);
        ViewBag.RoleNames = await UserManager.GetRolesAsync(user.Id);
        return View(user);
    }
    // Return Error:
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}

另一方面,我不想改变逻辑,只想改变 if 块中的条件,但我不确定检查 int 的空值的最佳方法是什么?

原来的方法是这样的:

if (id == null) //id is string

由于我必须将字符串更改为 int 类型,因此我需要检查 null 类似的内容:

if (id !> 0) //id is int 

有什么想法吗?

【问题讨论】:

  • Int 不能为空,最好的办法是使用 -1 作为空值(假设永远不会正常使用)
  • If (id == 0)。但最好将其设为int?(可为空),以便您可以使用if (!id.HasValue)
  • 这个问题不清楚。你展示的方法是一个action方法,所以是通过MVC调用的。您有哪些预期的用例?你有什么错误处理?如果用户在调用此操作方法时省略了id 参数会发生什么?当他们请求将id 设置为0 的页面时,您希望发生什么?你真正想做什么?
  • @StephenMuecke 我不应该使用可为空的 int 作为 id 参数也依赖。那么,使用 if (id == 0) 而不是 if (id == null) 可以吗?谢谢...
  • 为什么不让它可以为空呢?但我假设你的数据库中不会有 id = 0 的记录,所以应该没问题。

标签: c# asp.net asp.net-mvc if-statement null


【解决方案1】:

一个普通的整数不能为空,默认值为0。如果你想要一个nullable integer你需要使用int?然后你可以像这样检查它是空还是0:

if (id == null) //!id.HasValue
{
    //some stuff
} else if(id == 0) {
    //other stuff
}

【讨论】:

  • 我不想使用 nullable,是否可以在没有 nullable 的情况下使用它?
  • @Clint 你在问 “一个不可为空的 int 可以为空吗”
  • @ClintEastwood 不,那是不可能的
  • @CodeCaster 好的,更新了。
  • 当然你可以检查你的int是否为0。
猜你喜欢
  • 1970-01-01
  • 2012-12-10
  • 2015-04-01
  • 2019-06-11
  • 2014-07-17
  • 1970-01-01
  • 2016-01-22
  • 1970-01-01
  • 2013-02-21
相关资源
最近更新 更多