C#强制转换:(int)、Int32.Parse() 和 Convert.toInt32()-转载

上一篇 / 下一篇  2011-04-16 09:35:02 / 个人分类:C#

本文介绍了C#强制转换问题,即(int)Int32.Parse() Convert.toInt32()的三种方法。

 

C#强制转换中,(int)Int32.Parse() Convert.toInt32() 三种方法有何区别?

int 关键字表示一种整型,是32位的,它的 .NET Framework 类型为 System.Int32

(int)表示使用显式强制转换,是一种类型转换。当我们从int类型到longfloatdouble decimal 类型,可以使用隐式转换,但是当我们从long类型到int类型转换就需要使用显式强制转换,否则会产生编译错误。

Int32.Parse()表示将数字的字符串转换为32 位有符号整数,属于内容转换[1]

我们一种常见的方法:public static int Parse(string)

如果string为空,则抛出ArgumentNullException 异常;

如果string格式不正确,则抛出FormatException 异常;

如果string的值小于MinValue或大于MaxValue的数字,则抛出OverflowException异常。

Convert.ToInt32() 则可以将多种类型(包括 object  引用类型)的值转换为 int  类型,因为它有许多重载版本[2]

1.  public static int ToInt32(object);  

2.   

3.   public static int ToInt32(bool);  

4.   

5.   public static int ToInt32(byte);  

6.   

7.   public static int ToInt32(char);  

8.   

9.   public static int ToInt32(decimal);  

10.  

11.  public static int ToInt32(double);  

12.  

13.  public static int ToInt32(short);  

14.  

15.  public static int ToInt32(long);  

16.  

17.  public static int ToInt32(sbyte);  

18.  

19.  public static int ToInt32(string);  

20.  

21.  ......  

(int)Int32.Parse(),Convert.ToInt32()三者的应用举几个例子:   

例子一:

1.  long longType = 100;  

2.  int intType  = longType;       // 错误,需要使用显式强制转换  

3.  int intType = (int)longType; //正确,使用了显式强制转换 

例子二:

4.  string stringType = "12345";   

5.  int intType = (int)stringType;     //错误,string 类型不能直接转换为 int  类型   

6. 

TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2024-05-14  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 1369
  • 日志数: 1
  • 建立时间: 2011-03-15
  • 更新时间: 2011-04-19

RSS订阅

Open Toolbar