常用类型转换 一.常用int类型转换 1.
int.parse(string) 这个类型只支持string类型
2. double doubleType = Int32.MaxValue + 1; int intType = (int)doubleType; //虽然运行正确,但是得出错误结果 int intType = Convert.ToInt32(doubleType) //抛出 OverflowException 异常
3.
string stringType = "1"; int intType = (int)stringType; //错误,string 类型不能直接转换为 int 类型 int intType = Int32.Parse(stringType); //正确
4.
long longType = 1; int intType = longType; // 错误,需要使用显式强制转换 int intType = (int)longType; //正确,使用了显式强制转换
5.
long longType = 1; string stringType = "1"; object objectType = "2"; int intType = Convert.ToInt32(longType); //正确 int intType = Convert.ToInt32(stringType); //正确 int intType = Convert.ToInt32(objectType); //正确
二.常用string类型转换 1.tostring()方法 当值确定的时候使用该方法 2.Convert.ToString() 当参数不确定的时候