C#隐式和显示类型转换

  C# 是在编译时静态类型化的,因此变量在声明后就无法再次声明,或者无法用于存储其他类型的值,除非该类型可以转换为变量的类型。 

1. 隐式类型转换
  隐式转换,就是系统默认的转换,其本质是小存储容量数据类型自动转换为大存储容量数据类型,该转换是一种安全类型的转换,不会导致数据丢失,因此不需要任何特殊的语法。

  下面是 .NET 数据类型之间的C#隐式转换列表:

  

2.显式类型转换

  显式类型转换,即强制类型转换。显式转换需要强制转换运算符,而且强制转换会造成数据丢失。

 源类型 目标类型
sbyte byte,ushort,uint,ulong,或char
 byte  sbyte或char
 short  sbyte,byte,ushort,uint,ulong,或char
 ushort  sbyte,byte,short,或char
 int  sbyte,byte,short,ushort,uint,ulong,或char
 uint  sbyte,byte,short,ushort,int,或char
 long  sbyte,byte,short,ushort,int,uint,ulong,或char
 ulong  sbyte,byte,short,ushort,int,uint,long,或char
 float  sbyte,byte,short,ushort,int,uint,long,ulong,char,或decimal
 double  sbyte,byte,short,ushort,int,uint,long,ulong,char,float,或decimal
 decimal  sbyte,byte,short,ushort,int,uint,long,ulong,char,float,或double
 char  sbyte,byte,或short

 

显示类型装换的方法:

1.前置类型转换,例如:

double dbTotal = 12345678910.456;
int i = (int)dbTotal;//此处运用了强制转换

2.类型解析转换,如int.parse(),int32.parse()等采用方法来转换.

string str = "100";
int i = int.Parse(str);

注意:str除掉引号的类型必须和*.Parse的类型一致。如果将100改成100.78,即变成float类型,运行时将会报错"输入字符串的格式不正确."

3.采用后缀式转换,如k.ToString(),一般运用于字符串或日期等其它类型

int i = 100;
string s = i.ToString();

4.采用Convert类来实现转换,该类基本支持所有类型之间的转换

string str = "100";
inti = Convert.ToInt32(str);

注意:str除掉引号的类型必须和Convert.*的类型一致。如果将100改成100.78,即变成float类型,运行时将会报错"输入字符串的格式不正确."

posted @ 2013-06-01 14:49  花落红尘  阅读(615)  评论(1编辑  收藏  举报