string locstr = 123.ToString();
//如果要将"locstr"转成整型数
//方法一: 用 Convert
int i = Convert.ToInt16(locstr);
//方法二: 用 Parse
int ii = int.Parse(locstr);
该方式也是将数字内容的字符串转换为int类型,但是该方式比int.Parse(string s) 好一些,它不会出现异常,最后一个参数result是输出值,如果转换成功则输出相应的值,转换失败则输出0。
classtest
{
staticvoid Main(string[] args)
{
string s1 = "abcd";
string s2 = "1234";
int a, b;
bool bo1 = int.TryParse(s1, out a);
Console.WriteLine(s1 + " " + bo1 + " " + a);
bool bo2 = int.TryParse(s2, out b);
Console.WriteLine(s2 + " " + bo2 + " " + b);
}
}
结果输出:
abcd False 0
1234 True 1234