C#中 int、Convert、Parse、TryParse 的区别对比
区别如下:
private void button1Event()
{
// int 变量名[强制类型转换]:
//1.从 int 类型到 long,float,double,decimal 类型,可以使用隐
式转换,但是从 long 类型到 int 类型就需要使用显式转换。
//2.可以进行 object 到 int 得转换,object 的值要赋予 int 类型的值,
否则会产生编译错误,而且 object 为 null 时也会出错。
//3.若使用 char 类型,返回的 ASCII 代码的值。
float fl = 25.25f; //浮点
object ol = "sd"; //对象为整形
object on = null; //对象为 null
char ci = 'a';
try
{
//int nf = (int)fl;
//int cn = (int)ci; //返回 ASCII 代码的值
//int no = (int)ol; //Exception 指定转换无效
//int non = (int)on; //未将对象引用到实例
}
catch (Exception ex)
{
MessageBox.Show("int 类型转换:" + ex.Message);
}
// int.Parse(string 类型变量名)
//1.字符串内容为空或者 null 时,则抛出 ArgumentNullException
异常。
//2.如果字符串内容不是数字,则抛出 FormatException 异常。
//3.如果字符串内容所表示数字超出 int 类型可表示的范围,则抛出
OverflowException 异常。
string s1 = null;
string s11 = string.Empty;
string s2 = "sdsds";
string s3 = "45544511121144554";
try
{
评论1
最新资源