非可空int可以为null吗?

时间:2016-10-25 08:55:54

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

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

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 

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

普通整数不能为空,默认值为0.如果您需要nullable integer,则需要使用int?然后您可以检查它是否为null或0如下:

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