黑马程序员技术交流社区

标题: 类型转换 [打印本页]

作者: 李朋朋    时间: 2012-7-18 23:28
标题: 类型转换
强制类型转换有几种?区别是什么?
作者: 邓戊庚    时间: 2012-7-19 00:07
我目前知道的就集中,在需要转换的变量前加(int)后面跟需要转换的,还有int.parse(需要转换的),另外就是conver.toint32(需要转换的)  int可以改成你需要转换成其他的变量.
另外to.string(),把其他的转换成string类型的
作者: 杨正    时间: 2012-7-19 00:47
本帖最后由 杨正 于 2012-7-19 22:47 编辑

在C#中,我现在学到的有三种强制类型转换,现在以强制转换成有符号32位整型为例,可以找到下面三种方式:
① (int)()                    ②Convert.ToInt32()                        ③int.Parse()

       三种转变在有些数据时可以通用,但是用法上仍然有很大的区别:
一、int() 表示使用显式强制转换,是一种类型转换。当我们从 int 类型到 long、float、double 或decimal 类型,可以使用隐式转换,但是当我们从 long 类型到 int  类型转换就需要使用显式强制转换,否则会产生编译错误。

二、Convert.ToInt32() 则可以将多种类型(包括 object  引用类型)的值转换为 int  类型,因为它有许多重载版本[2]:
    public static int ToInt32(object);
    public static int ToInt32(bool);
    public static int ToInt32(byte);
    public static int ToInt32(char);
    public static int ToInt32(decimal);
    public static int ToInt32(double);
    public static int ToInt32(short);
    public static int ToInt32(long);
    public static int ToInt32(sbyte);
    public static int ToInt32(string);

三、Int32.Parse()表示将包含数字的字符串转换为32 位有符号整数,属于内容转换
    我们一种常见的方法:public static int Parse(string)。
    如果 string 为空,则抛出 ArgumentNullException 异常;
    如果 string 格式不正确,则抛出 FormatException 异常;
    如果 string 的值小于 MinValue 或大于 MaxValue 的数字,则抛出 OverflowException 异常。

可以看出来,Convert.ToInt32() 的功能是最强大的,它把Int32.Parse()功能包括了,也是说是Int32.Parse()是Convert.ToInt32() 的一种特殊情况。
作者: 赵鹏程    时间: 2012-7-19 23:10
在C#中除了string类型外,其他的所有基本类型都有parse方法,用来将string类型转换成相应的类型,int.parse就是将string类型转换成int类型。
convert.toint32方法是将double、single等数据类型转换成int类型。
而强制类型转换才使用()




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2