关于int.TryParse的使用

本文通过实例演示了C#中int.TryParse方法的使用技巧,包括如何判断字符串是否可以转换为整数,并提供了自定义TryParse方法的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace ConsoleApplication7
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             string TP = "123abc";
14             string TPE = "123";
15             int re,ret;
16             //测试转换失败
17             if (int.TryParse(TP, out re) == true)
18             {
19                 Console.WriteLine("{0}能转换成功,转换后的数为:{1}",TP,re );
20             }
21             else
22             {
23                 Console.WriteLine("{0}转换失败",TP);
24             }
25             //暂停
26             Console.ReadKey();
27             Console.WriteLine();
28             //测试转换成功
29             if (int.TryParse(TPE, out ret) == true)
30             {
31                 Console.WriteLine("{0}能转换成功,转换后的数为:{1}" ,TPE,ret);
32             }
33             else
34             {
35                 Console.WriteLine("{0}转换失败",TPE);
36             }
37             //暂停
38             Console.ReadKey();
39         }
40     }
41 }

 实现int.TryParse的原理:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace ConsoleApplication7
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             int re;
14             string s = "1233";
15             if (IntTryParse(s, out re))
16             {
17                 Console.WriteLine("转换成功!" + re);
18                 Console.ReadKey();
19             }
20             else
21             {
22                 Console.WriteLine("转换失败!");
23                 Console.ReadKey();
24             }
25         }
26 
27         static bool IntTryParse(string s, out int result)//模仿TryParse定义方法IntTryParse
28         {
29             result = 0;
30             try
31             {
32                 result = Convert.ToInt32(s);
33                 return true;
34             }
35             catch
36             {
37                 return false;
38             }
39         }
40     }
41 }

 

转载于:https://www.cnblogs.com/start-from-scratch/p/5056675.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值