关于int.TryParse的使用

老余博客

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication7
{
    class Program
    {
        static void Main(string[] args)
        {
            string TP = "123abc";
            string TPE = "123";
            int re,ret;
            //测试转换失败
            if (int.TryParse(TP, out re) == true)
            {
                Console.WriteLine("{0}能转换成功,转换后的数为:{1}",TP,re );
            }
            else
            {
                Console.WriteLine("{0}转换失败",TP);
            }
            //暂停
            Console.ReadKey();
            Console.WriteLine();
            //测试转换成功
            if (int.TryParse(TPE, out ret) == true)
            {
                Console.WriteLine("{0}能转换成功,转换后的数为:{1}" ,TPE,ret);
            }
            else
            {
                Console.WriteLine("{0}转换失败",TPE);
            }
            //暂停
            Console.ReadKey();
        }
    }
}

实现int.TryParse的原理:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication7
{
    class Program
    {
        static void Main(string[] args)
        {
            int re;
            string s = "1233";
            if (IntTryParse(s, out re))
            {
                Console.WriteLine("转换成功!" + re);
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("转换失败!");
                Console.ReadKey();
            }
        }

        static bool IntTryParse(string s, out int result)//模仿TryParse定义方法IntTryParse
        {
            result = 0;
            try
            {
                result = Convert.ToInt32(s);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}

其实当看了 实现int.TryParse的原理 之后应该就明白无非就是使用了强制转换,Convert.ToInt32  这个方法进行强制封装了而已;

赞(1)
分享
文章版权声明:除非注明,否则均为老余个人博客原创文章,转载或复制请以超链接形式并注明出处。

发表评论

评论列表
取消
微信二维码
微信二维码
支付宝二维码
取消
老余博客微信公众号二维码