为什么解析函数返回o?

时间:2016-05-28 12:11:19

标签: c#

我是c#编程的新手,我最近碰到了一个看起来非常基本的问题。我将字符串值SV_1存储在变量lastServiceNo中并使用Split函数将其拆分,结果存储在名为index.Basically的字符串数组中index [1]有一些数值bt作为字符串。现在我想将字符串转换为int。在下面的代码中,它会遇到预期的行为,直到遇到解析函数。我无法理解为什么这个解析函数返回0,因为索引[1]中有一些数值。有人可以指出问题吗?

public string GenerateServiceNo() {
    DataAccessLayer.DataAccessLayer dlObj= new DataAccessLayer.DataAccessLayer();
    string lastServiceNo = dlObj.GetLastServiceNo();
    string[] index = lastServiceNo.Split('_');
    int lastIndex = int.Parse(index[1]);
    return "SV_"+(lastIndex++).ToString();
}

1 个答案:

答案 0 :(得分:0)

int.Parse(string s)如果数字在数据大小方面过于错误或字符串“s”的数字格式不正确,则会引发异常。

此方法接受的格式为 [ws] [sign] 数字 [ws] 其中:

  • [ws]对于一个或多个空格(“”)
  • 是可选的
  • [sign]对于“+”或“ - ”
  • 是可选的

检查here以获取完整参考。

如上所述,我可以向你保证,如果int.Parse(index [1])返回0,则表示index [1]等于“[ws] [sign] 0 [ws]”使用上面的记录。

然而,看一下你的代码,我可以得出结论,你在赋值后递增一个局部变量而不使用之后增加的值。也许你的意思是这个操作不应该是0?

如果是这种情况,那么我相信这就是你想要实现的目标:

public string GenerateServiceNo() 
{
    DataAccessLayer.DataAccessLayer dlObj= new DataAccessLayer.DataAccessLayer();

    string lastServiceNo = dlObj.GetLastServiceNo();
    string[] index = lastServiceNo.Split('_');
    int lastIndex = int.Parse(index[1]);

    return string.Format("SV_{0}", ++lastIndex);
}

假设index [1] ==“0”,此方法现在将返回“SV_1”。

相关问题