隐式转换
首先,我们先看整型与浮点型
C#中的整型包括有(只列出有符号):sbyte、short、int、long
浮点型则有:float、double、decimal
整型各个类型之间的转换如果发生在从小到大,那么不需要进行修饰C#自身就可以完成类型转换。
注意:整型数据也可以隐式转换成浮点型。
例如:
static void Main(string[] args)
{
//隐式转换
//整型、浮点型
//声明一个sbyte变量
sbyte score = 10;
//隐式转换为short
short myScore = score;
//short--->int
int classScore = myScore;
//int--->long
long allScore = classScore;
//int--->float
float floatScore = classScore;
//float--->double
double doubleScore = floatScore;
}
隐式转换没有什么需要特别注意的地方。
强制转换(显式转换)
显示转换需要强制转换运算符。由大到小需要用强制转换,这样需要付出缺失精度的代价,甚至数据的错误。
转换的方法就是再要转换的变量前加(要转的类型);
例如:short—>sbyte
0000 0001 0000 0110 —> 0000 0110
就丢失了数据。
//强制转换
int damage = 1000000;
//int --> sbyte
sbyte health = (sbyte)damage;
//输出结果
Console.WriteLine(health);
float mathScore = 90.5f;
//float --> int
int myAllScore = (int)mathScore;
//会把⼩数点后⾯的内容全部舍去
Console.WriteLine(myAllScore);
Int和char之间的转换
//int 和 char之间的类型转换
int num = 11101;
//int --> char
char letter = (char)num;
//a-97
Console.WriteLine(letter);
Int与bool之间不能转换
String与其他类型的转换
String的转换较为特殊,需要通过方法进行
转换方法
System.Convert
System.Convert.ToBoolean()
System.Convert.ToInt32()
System.Convert.ToSingle()
System.Convert.ToDouble()
System.Convert.ToChar()
或者使用数据类型.parse()
int.Parse()
bool.Parse()
float.Parse()
char.Parse()
其他类型转成字符串
直接用其他类型的变量.ToString();