C#_6

显式转换

括号转换:

作用:将高精度(范围大)的类型强制转换为低精度(范围小)

语法:变量类型 变量名=(变量类型)变量;

注意:精度问题 范围问题

例子:

        sbyte sb=1;

int i=(int)sb;

Parse:

作用:把字符串类型转换为对应的类型
语法:变量类型.Parse("字符串")  字符串为对应变量类型
注意:字符串必须能够转换成对应类型 否则报错

例子:

int i=int.Parse("123");  正确 123 整数

int i=int.Parse("123.8");  错误 123.8 

Convert:

作用:更准确的将各个类型之间进行相互转换
语法:Convert.To目标类型(变量或常量)
注意:填写的变量或常量必须正确 否则出错

例子:

int i = Convert.ToInt32("12");  int 4字节 32位 

uint ui = Convert.ToUInt32("1");

short s = Convert.ToInt16("1");  short 2字节 16位

ushort us = Convert.ToUInt16("1");

float f = Convert.ToSingle("13.2");//single 单一的

string s = Convert.ToString(123123);

其他类型转字符串

语法:变量.ToString();

例子:

int i=5;

string str6 = i.ToString();

特殊:

          //进行字符串拼接时  若有字符串参与拼接 非字符串会自动调用Tostring() 转换成字符串

          Console.WriteLine("123123" + 1 + true);

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/unitywyb/p/14499148.html