c#类型转换
c#数据类型的转换分为两种类型:
隐式类型转换和显式类型转换
1.隐式类型转换
将小范围的类型转换为大范围的类型,如将int类型转换为float类型,派生类转换为基类。
例子:
int i = 2; float f = i;
class class1{
}
class class2 : class1
{
}
class1 c1 = new class2();
2.显示类型转换
即强制类型转换,这种转换需要强制转换运算符,并且转换可能会造成数据丢失。如大范围类型转换为小范围类型,基类转换为派生类。
例子:
float f = 2.23; int i = f;
class class1{
}
class class2 : class1{
}
class2 c2 = new class1();
3.c#类型转换方法:
ToBoolean、ToByte、 ToChar 、 ToDateTime、ToDecimal、ToString、ToType ......
4.将其他类型转换为整数类型的方法:Convert 、Parse 、 TryParse(string s,out int i)
String str = abc;
int i = Convert.ToInt32(str);
int i1 = int.Parse(str);
int i2 =int.TryParse(str,int a);
其中int.TryParse是第一个参数是被转换的类型,第二个是输出的结果,如转换成功则输出1,失败则输出0;
当Convert.ToInt32()接收到的参数为空时,会返回0;而当int.Parse()接收到的参数为空时,会返回异常。因此建议使用int.Parse,而不用Convert.ToInt32();
对double类型的数据取整,使用Convert.ToInt32可以四舍五入,而使用int强制类型转换则直接去掉小数点后面的数据。