string a="1234";
int b=int.Parse(a);
如果a="124gfjn"
这样在运行的时候就会出错
如何才能检测 一个字符串能否转换成为整型呢?

解决方案 »

  1.   

    int val = 0;
    if(!int.TryParse(a, out val))
    {
       // 转换失败
    }
      

  2.   


    int b=0;
    try{
    b=int.Parse(a); 
    }catch{
    转换失败
    }
      

  3.   

    int b=0;
    string a=string.empty;
    try
    {
        b=int.parse(a);
    }
    catch(System.FormatException)
    {
        MessageBox.show("转换失败");
    }
      

  4.   

                try
                {
                    string a = "1234aasd";
                    int b = int.Parse(a);
                    Console.WriteLine(b);
                }
                catch (Exception ee)
                {
                    Console.WriteLine(ee.Message);
                }
      

  5.   

    用捕获异常来实现
    try
    {
      //转换代码
    }
    catch
    {
      //出错信息
    }
      

  6.   

    定义一个正则表达式
    进行整数匹配;        static void Main(string[] args)
            {
                if (isInt("123"))
                {
                    //Todo
                }
                else { 
                    // Todo
                }
            }
            public static bool isInt(string str)
            {
                Regex r = new Regex("数字的正则表达式");
                if (r.IsMatch(str))
                {
                    return true;
                }
                else {
                    false;
                }
            }