显示转换和隐式转换
隐式转换
隐式转换就是不需要声明就能进行的转换,小范围数值转换成大范围数值
byte b = 10;
int i = 500;
i = b;
Console.WriteLine(i);
显式转换
显式转换也可以称为强制转换,需要在代码中明确地声明要转换的类型。
如果要在不存在隐式转换的类型之间进行转换,就需要使用显式转换
大范围数值转换成小范围数据,需要强制转换
byte b = 10;
int i = 500;
b = (byte)i;
Console.WriteLine(b);//数值超出范围,结果错误
i = 111;
b = (byte)i;
Console.WriteLine(b);//结果正确
double x = 19810927.0112; //建立double类型变量x
int y = (int)x; //显示转换成整型变量y
Console.WriteLine(y); //输出整型变量y
Console.ReadLine();
方法
字符串=》数字
类型.Parse(需要转换的值)
Convert.ToInt32("123");
string str = Console.ReadLine();
int a1 = int.Parse(str);
Console.WriteLine(a1 + 20);
float f = float.Parse(str);
double d = double.Parse(str);
数字=》字符串
数字.ToString()
string str = Console.ReadLine();
int a1 = Convert.ToInt16(str);
Console.WriteLine(a1 + 10);
float f = Convert.ToSingle(str);//转换成float
double d = Convert.ToDouble(str);
float a = 10.00000f;
string str1 = "" + a;
string str2 = a.ToString();
Console.WriteLine(str2);
string str3 = a.ToString("0.00");//保留两位小数
Console.WriteLine(str3);
as
as强制转换,转换失败也不会抛异常
装箱和拆箱
将值类型转换为引用类型的过程叫做装箱,相反,将引用类型转换为值类型的过程叫做拆箱
int i = 2008;
object obj = i;
Console.WriteLine("1、i的值为{0},装箱之后的对象为{1}", i, obj);
i = 927;
Console.WriteLine("2、i的值为{0},装箱之后的对象为{1}", i, obj);
Console.ReadLine();
int i = 112;
object obj = i;
Console.WriteLine("装箱操作:值为{0},装箱之后对象为{1}", i, obj);
int j = (int)obj;
Console.WriteLine("拆箱操作:装箱对象为{0},值为{1}", obj, j);
Console.ReadLine();
object obj;
//装箱:值类型转换成引用类型
int a = 10;
obj = a;
//上传数据obj
//后台接收obj
//拆箱:引用类型转换成值类型
int b = (int)obj;
Console.WriteLine(b);
白盒
黑盒
ASCII码转成字符
(Char)+i
实例:大写字母转小写字母
输入一个字母,如果输入的是小写字母,则转换成大写字母输出,如果输入的是大写字母则转换成小写字母输出
int i = Console.Read();//接收我们输入的ASCII
if (i >= 97 && i <= 122)
{
i = i - 32;
Console.WriteLine((char)i);
}
else if (i >= 65 && i <= 90)
{
i = i + 32;
Console.WriteLine((char)i);
}