博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
tryParse 检测入参是否是数字
阅读量:694 次
发布时间:2019-03-17

本文共 1047 字,大约阅读时间需要 3 分钟。

C#里面有一个TryParse方法非常方便,这里用int.TryParse来做示例

既可以用来判断输入字符串能否转化成指定的数据类型, 又可以同时将转化的结果用out类型参数进行输出

string testStr1 = "1";            string testStr2 = "str2";            int testInt1;            bool reuslt1 = int.TryParse(testStr1, out testInt1);            int testInt2;            bool result2 = int.TryParse(testStr2, out testInt2);            Console.WriteLine("testInt1=" + testInt1);            Console.WriteLine("testInt2=" + testInt2);            Console.WriteLine("reuslt1=" + reuslt1);            Console.WriteLine("result2=" + result2);            if(int.TryParse(testStr1,out testInt1))            {                Console.WriteLine("testStr1是数字" + testInt1);            }            else            {                Console.WriteLine("testStr1不是数字"+testStr1);            }            if (int.TryParse(testStr2, out testInt2))            {                Console.WriteLine("testStr2" + testInt2);            }            else            {                Console.WriteLine("testStr2不是数字"+testStr2);            }            Console.ReadLine();

 

转载地址:http://ygbez.baihongyu.com/

你可能感兴趣的文章