C# TryParse (int, double, float) 用法示例
使用C# TryParse方法,看看能否将字符串转换为数字。
在字符串处理过程中,经常需要将写好的字符串式的数字转换成int或long类型,以便进行数字运算。将数值类型转换为string类型不成问题,但是反过来就不可能了,并且可能会返回异常,必须对其进行检查以避免异常。
什么时候使用TryParse函数
C#的TryParse函数可以处理各种类型,包含double,long,int 和byte类型。这些函数都会检查参数是否可以转换为目标类型,如果可以,则返回Ture,否则返回False。
尝试转换为一个不能转换的类型将会触发一个异常,但是TryParse函数仅会返回False,所以没必要捕捉更多异常。
因为异常处理要耗费大量的编码时间和过程加载,所以在转换之前使用TryParse来检查是否可以转换会更有效率。
如何使用TryParse函数
当使用TryParse函数时,有两个参数是需要指定的。string类型的字符串检查是放在第一个参数,要转换成的各种类型放置在第二个参数,但是“out”是加在第二个参数前面的。如果转换成功,则转换后的数值会输入到第二个参数的变量中,所以不需要费心地检查然后再次转换。如果转换失败,则分配数值0。
1 using System; 2 namespace CSharp_TryParse_Example 3 { 4 public class Program 5 { 6 public static void Main(string[] args) 7 { 8 string str1 = "120", str2 = "120.10", str3 = "s120"; 9 int convertedInt1, convertedInt2, convertedInt3; 10 //True 11 Console.WriteLine("Conversion: {0}, converted value: {1}", 12 int.TryParse(str1, out convertedInt1), convertedInt1); 13 //False 14 Console.WriteLine("Conversion: {0}, converted value: {1}", 15 int.TryParse(str2, out convertedInt2), convertedInt2); 16 //False 17 Console.WriteLine("Conversion: {0}, converted value: {1}", 18 int.TryParse(str3, out convertedInt3), convertedInt3); 19 // 20 string str4 = "120.30"; 21 string str5 = "120.40"; 22 double convertedDouble; 23 float convertedFloat; 24 //True 25 Console.WriteLine("Conversion: {0}, converted value: {1}", 26 double.TryParse(str4, out convertedDouble), convertedDouble); 27 //True 28 Console.WriteLine("Conversion: {0}, converted value: {1}", 29 float.TryParse(str5, out convertedFloat), convertedFloat); 30 } 31 } 32 }
Conversion: True, converted value: 120 Conversion: False, converted value: 0 Conversion: False, converted value: 0 Conversion: True, converted value: 120.3 Conversion: True, converted value: 120.4

浙公网安备 33010602011771号