如何在C#中将字符串值转换为int [英] how to convert a string value to int in C#
本文介绍了如何在C#中将字符串值转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
OI如何在C#中将字符串值转换为整数?
我需要将ID转换为整数.
How do OI convert string value to integer in C#?
I need to convert IDs here to integer.
string[] IDs = hdnFldSelectedValues.Value.Trim().Split(''|'');
推荐答案
方法如下:
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.
同样,抛出异常更好.
In last example, failure to parse a string will be converted to -1.
Again, throwing exception is better.
List<int> list = new List<int>();
foreach (string id in IDs)
{
int result;
if (int.TryParse(id, out result))
list.Add(result);
}
这篇关于如何在C#中将字符串值转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文