且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中将字符串值转换为int

更新时间:2021-10-26 01:40:35

方法如下:

This is how:

string[] IDs = hdnFldSelectedValues.Trim().Split('|');
int[] Values = new int[IDs.Length];
for(int index = 0; index < Values.Length; index++)
    Values[index] = int.Parse(IDs[index]);



此代码将对超出范围的第一个无效数字格式引发异常.如果无效格式应转换为表示错误的特殊值(不建议),请使用int.TryParse:



This code will throw exception on first invalid numeric format of out of range. If invalid format should be converted to a special value indicating error (not recommended) use int.TryParse:

string[] IDs = hdnFldSelectedValues.Trim().Split('|');
int[] Values = new int[IDs.Length];
for(int index = 0; index < Values.Length; index++) {
    int value;
    if (!int.TryParse(IDs[index], out value))
        value = -1;
    Values[index] = value;
} //loop index



在最后一个示例中,无法解析字符串将转换为-1.
同样,抛出异常更好.

-SA



In last example, failure to parse a string will be converted to -1.
Again, throwing exception is better.

—SA


List<int> list = new List<int>();
foreach (string id in IDs)
{
    int result;
    if (int.TryParse(id, out result))
        list.Add(result);
}