TryParse用法

int.Parse()是一种类型转换;表示将数字内容的字符串转为int类型。 如果字符串为空,则抛出ArgumentNullException异常; 如果字符串内容不是数字,则抛出FormatException异常; 如果字符串内容所表示数字超出int类型可表示的范围,则抛出OverflowException异常;
int.TryParse 与 int.Parse 又较为类似,但它不会产生异常,转换成功返回 true,转换失败返回 false。最后一个参数为输出值,如果转换失败,输出值为 0

TryParse的用法Demo:

        /// <summary>
        /// 测试TryParsse的用法
        /// </summary>
        public static void TestTryParse() {
            string strTemp = "3";
            int intTemp = 0;
            Console.WriteLine(int.TryParse(strTemp, out intTemp));
            Console.WriteLine(intTemp);

            strTemp = "Hello";
            Console.WriteLine(int.TryParse(strTemp, out intTemp));
            Console.WriteLine(intTemp);
        }
Output:
image
posted @ 2013-07-30 16:46  李楊  阅读(1033)  评论(0编辑  收藏  举报