为什么将字符串转换或解析为int返回零?

时间:2011-04-03 13:24:59

标签: c# asp.net-mvc asp.net-mvc-3 entity-framework-4

为什么将字符串转换/解析为int返回0/0?

在调试时,使用断点,我可以看到“3”作为字符串值发布到浏览操作但是当我如上所述转换为int时,该值将转换为int类型的0值。

    //
    // GET: /Event/Browse
    public ActionResult Browse(string category)
    {
        int id = Convert.ToInt32(category);


        // Retrieve Category and its Associated Events from database
        var categoryModel = storeDB.Categories.Include("Events").Single(g => g.CategoryId == id);
        return View(categoryModel);
    }

请查看下面的图片以便更好地理解: enter image description here

另一个图像 - categoryModel在LINQ查询中变为null。 enter image description here

2 个答案:

答案 0 :(得分:4)

来自Int32.TryParse上的MSDN here

  

当此方法返回时,包含   等效的32位有符号整数值   到s中包含的数字,如果是   转换成功,或者为零   转换失败。转换   如果s参数为nullptr则失败,   格式不正确,或   表示小于MinValue的数字   或大于MaxValue。这个   参数未经初始化传递。

答案 1 :(得分:3)

如果您的Parse()调用失败并且您的异常未被捕获或者您没有测试TryParse()的返回值,那么int变量肯定会保持原样 - 默认情况下初始化为零。

例如,这会使你的int保持为零:

int i;
Int32.Parse("FAIL!");
// i is still a zero.

所以请试试这个:

int i;
bool parseSuccessful = Int32.TryParse("123", out i);
// parseSuccessful should be true, and i should be 123.

或者看到它优雅地失败:

int i;
bool parseSuccessful = Int32.TryParse("FAIL!", out i);
// parseSuccessful should be false, and i should be 0.