超出范围异常 - 子串 - C#

时间:2015-01-28 12:22:06

标签: c# regex

我有一些电话号码列表,其中一些有扩展名,有些则没有。 我正式使用我的电话号码只返回数字。

然后我为前10位数字创建一个字符串(区号+数字)。

我比较这个字符串长度并将其与原始字符串进行比较。 如果存在差异,我会将余数用作扩展名。

在下面的代码中,我一直在超出范围异常。我调试了它,它似乎没有超出范围。任何人都能看到我失踪的东西?

var prePhone = emp.y.PhoneNumber;

if (!string.IsNullOrEmpty(prePhone))
{
    string xPhone = Regex.Replace(prePhone, "[^0-9]", "");
    string number = xPhone.Substring(0, 10);
    int extMath = xPhone.Length - number.Length;

    if (extMath >= 1)
    {   int preExt = 9 + extMath;
        string ext = xPhone.Substring(10, preExt);//Out of range exception
        em.Phone = beautifyPhoneNumber(number, ext);
    }
    else {
        string ext = null;
        em.Phone = beautifyPhoneNumber(number, ext);
    }
}

1 个答案:

答案 0 :(得分:4)

string ext = xPhone.Substring(10, preExt)

第二个参数不是结束索引,而是要提取的字符串的长度。

自preExt>在您的代码中,xPhone的长度必须超过20个字符(因为您从索引10开始),否则将抛出异常。