类型转换
之前我们提到过,当相互转化的类型不兼容时,我们会用到Convert来进行类型转换;
但有时接收的内容,不可以进行类型转换,例如,输入123abc,转换成int类型;这样的话需要会抛异常,需要进行异常处理;
string a = "123abc"; int b = Convert.ToInt32(a); Console.WriteLine(b); Console.ReadKey();
上述代码会抛出异常
下面我们将继续来介绍当类型不兼容时,转换的函数方法;
1.int.parse()【数据类型.parse()】
这个方法和Convert作用相同,但是效率更快一些;因为调用Convert来进行类型转化,实质也是Convert去调用int.parse();但是还是会抛出异常;代码如下:
string a = "123abc"; int b = int.Parse(a); Console.WriteLine(b); Console.ReadKey();
2.int.Tryparse(需要转换的变量,out 赋值的变量)【数据类型.Tryparse(需要转换的变量,out 赋值的变量)】
这个方法的使用更好一些,因为即使数据之间不可以转换,他也不会抛出异常;
string a = "123abc"; int b=5; bool c = int.TryParse(a,out b); Console.WriteLine(b); Console.ReadKey();

浙公网安备 33010602011771号